i2c_cxx.hpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. /*
  2. * SPDX-FileCopyrightText: 2020-2021 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #pragma once
  7. #ifndef __cpp_exceptions
  8. #error I2C class can only be used when __cpp_exceptions is enabled. Enable CONFIG_COMPILER_CXX_EXCEPTIONS in Kconfig
  9. #endif
  10. #include <exception>
  11. #include <memory>
  12. #include <chrono>
  13. #include <vector>
  14. #include <list>
  15. #include <future>
  16. #include "driver/i2c.h"
  17. #include "esp_exception.hpp"
  18. namespace idf {
  19. struct I2CException : public ESPException {
  20. I2CException(esp_err_t error);
  21. };
  22. struct I2CTransferException : public I2CException {
  23. I2CTransferException(esp_err_t error);
  24. };
  25. /**
  26. * Superclass for all transfer objects which are accepted by \c I2CMaster::transfer().
  27. */
  28. template<typename TReturn>
  29. class I2CTransfer {
  30. protected:
  31. /**
  32. * Wrapper around i2c_cmd_handle_t, makes it exception-safe.
  33. */
  34. struct I2CCommandLink {
  35. I2CCommandLink();
  36. ~I2CCommandLink();
  37. i2c_cmd_handle_t handle;
  38. };
  39. public:
  40. /**
  41. * Helper typedef to facilitate type resolution during calls to I2CMaster::transfer().
  42. */
  43. typedef TReturn TransferReturnT;
  44. /**
  45. * @param driver_timeout The timeout used for calls like i2c_master_cmd_begin() to the underlying driver.
  46. */
  47. I2CTransfer(std::chrono::milliseconds driver_timeout = std::chrono::milliseconds(1000));
  48. virtual ~I2CTransfer() { }
  49. /**
  50. * Do all general parts of the I2C transfer:
  51. * - initialize the command link
  52. * - issuing a start to the command link queue
  53. * - calling \c queue_cmd() in the subclass to issue specific commands to the command link queue
  54. * - issuing a stop to the command link queue
  55. * - executing the assembled commands on the I2C bus
  56. * - calling \c process_result() to process the results of the commands or calling process_exception() if
  57. * there was an exception
  58. * - deleting the command link
  59. * This method is normally called by I2CMaster, but can also be used stand-alone if the bus corresponding to
  60. * \c i2c_num has be initialized.
  61. *
  62. * @throws I2CException for any particular I2C error
  63. */
  64. TReturn do_transfer(i2c_port_t i2c_num, uint8_t i2c_addr);
  65. protected:
  66. /**
  67. * Implementation of the I2C command is implemented by subclasses.
  68. * The I2C command handle is initialized already at this stage.
  69. * The first action is issuing the I2C address and the read/write bit, depending on what the subclass implements.
  70. * On error, this method has to throw an instance of I2CException.
  71. *
  72. * @param handle the initialized command handle of the I2C driver.
  73. * @param i2c_addr The slave's I2C address.
  74. *
  75. * @throw I2CException
  76. */
  77. virtual void queue_cmd(i2c_cmd_handle_t handle, uint8_t i2c_addr) = 0;
  78. /**
  79. * Implementation of whatever neccessary action after successfully sending the I2C command.
  80. * On error, this method has to throw an instance of I2CException.
  81. *
  82. * @throw I2CException
  83. */
  84. virtual TReturn process_result() = 0;
  85. /**
  86. * For some calls to the underlying driver (e.g. \c i2c_master_cmd_begin() ), this general timeout will be passed.
  87. */
  88. const TickType_t driver_timeout;
  89. };
  90. /**
  91. * @brief Super class for any I2C master or slave
  92. */
  93. class I2CBus {
  94. public:
  95. /*
  96. * @brief Initialize I2C master bus.
  97. *
  98. * Initialize and install the bus driver in master mode.
  99. *
  100. * @param i2c_number The I2C port number.
  101. */
  102. I2CBus(i2c_port_t i2c_number);
  103. /**
  104. * @brief uninstall the bus driver.
  105. */
  106. virtual ~I2CBus();
  107. /**
  108. * The I2C port number.
  109. */
  110. const i2c_port_t i2c_num;
  111. };
  112. /**
  113. * @brief Simple I2C Master object
  114. *
  115. * This class provides to ways to issue I2C read and write requests. The simplest way is to use \c sync_write() and
  116. * sync_read() to write and read, respectively. As the name suggests, they block during the whole transfer.
  117. * For all asynchrounous transfers as well as combined write-read transfers, use \c transfer().
  118. */
  119. class I2CMaster : public I2CBus {
  120. public:
  121. /**
  122. * Initialize and install the driver of an I2C master peripheral.
  123. *
  124. * Initialize and install the bus driver in master mode. Pullups will be enabled for both pins. If you want a
  125. * different configuration, use configure() and i2c_set_pin() of the underlying driver to disable one or both
  126. * pullups.
  127. *
  128. * @param i2c_number The number of the I2C device.
  129. * @param scl_gpio GPIO number of the SCL line.
  130. * @param sda_gpio GPIO number of the SDA line.
  131. * @param clock_speed The master clock speed.
  132. * @param scl_pullup Enable SCL pullup.
  133. * @param sda_pullup Enable SDA pullup.
  134. *
  135. * @throws I2CException with the corrsponding esp_err_t return value if something goes wrong
  136. */
  137. I2CMaster(i2c_port_t i2c_number,
  138. int scl_gpio,
  139. int sda_gpio,
  140. uint32_t clock_speed,
  141. bool scl_pullup = true,
  142. bool sda_pullup = true);
  143. /**
  144. * Delete the driver.
  145. */
  146. virtual ~I2CMaster();
  147. /**
  148. * Issue an asynchronous I2C transfer which is executed in the background.
  149. *
  150. * This method uses a C++ \c std::future as mechanism to wait for the asynchronous return value.
  151. * The return value can be accessed with \c future::get(). \c future::get() also synchronizes with the thread
  152. * doing the work in the background, i.e. it waits until the return value has been issued.
  153. *
  154. * The actual implementation is delegated to the TransferT object. It will be given the I2C number to work
  155. * with.
  156. *
  157. * Requirements for TransferT: It should implement or imitate the interface of I2CTransfer.
  158. *
  159. * @param xfer The transfer to execute. What the transfer does, depends on it's implementation in
  160. * \c TransferT::do_transfer(). It also determines the future template of this function, indicated by
  161. * \c TransferT::TransferReturnT.
  162. *
  163. * @param i2c_addr The address of the I2C slave device targeted by the transfer.
  164. *
  165. * @return A future with \c TransferT::TransferReturnT. It depends on which template type is used for xfer.
  166. * In case of a simple write (I2CWrite), it's future<void>.
  167. * In case of a read (I2CRead), it's future<vector<uint8_t> > corresponding to the length of the read
  168. * operation.
  169. * If TransferT is a combined transfer with repeated reads (I2CComposed), then the return type is
  170. * future<vector<vector<uint8_t> > >, a vector of results corresponding to the queued read operations.
  171. *
  172. * @throws I2CException with the corrsponding esp_err_t return value if something goes wrong
  173. * @throws std::exception for failures in libstdc++
  174. */
  175. template<typename TransferT>
  176. std::future<typename TransferT::TransferReturnT> transfer(std::shared_ptr<TransferT> xfer, uint8_t i2c_addr);
  177. /**
  178. * Do a synchronous write.
  179. *
  180. * All data in data will be written to the I2C device with i2c_addr at once.
  181. * This method will block until the I2C write is complete.
  182. *
  183. * @param i2c_addr The address of the I2C device to which the data shall be sent.
  184. * @param data The data to send (size to be sent is determined by data.size()).
  185. *
  186. * @throws I2CException with the corrsponding esp_err_t return value if something goes wrong
  187. * @throws std::exception for failures in libstdc++
  188. */
  189. void sync_write(uint8_t i2c_addr, const std::vector<uint8_t> &data);
  190. /**
  191. * Do a synchronous read.
  192. * This method will block until the I2C read is complete.
  193. *
  194. * n_bytes bytes of data will be read from the I2C device with i2c_addr.
  195. * While reading the last byte, the master finishes the reading by sending a NACK, before issuing a stop.
  196. *
  197. * @param i2c_addr The address of the I2C device from which to read.
  198. * @param n_bytes The number of bytes to read.
  199. *
  200. * @return the read bytes
  201. *
  202. * @throws I2CException with the corrsponding esp_err_t return value if something goes wrong
  203. * @throws std::exception for failures in libstdc++
  204. */
  205. std::vector<uint8_t> sync_read(uint8_t i2c_addr, size_t n_bytes);
  206. /**
  207. * Do a simple asynchronous write-read transfer.
  208. *
  209. * First, \c write_data will be written to the bus, then a number of \c read_n_bytes will be read from the bus
  210. * with a repeated start condition. The slave device is determined by \c i2c_addr.
  211. * While reading the last byte, the master finishes the reading by sending a NACK, before issuing a stop.
  212. * This method will block until the I2C transfer is complete.
  213. *
  214. * @param i2c_addr The address of the I2C device from which to read.
  215. * @param write_data The data to write to the bus before reading.
  216. * @param read_n_bytes The number of bytes to read.
  217. *
  218. * @return the read bytes
  219. *
  220. * @throws I2CException with the corrsponding esp_err_t return value if something goes wrong
  221. * @throws std::exception for failures in libstdc++
  222. */
  223. std::vector<uint8_t> sync_transfer(uint8_t i2c_addr,
  224. const std::vector<uint8_t> &write_data,
  225. size_t read_n_bytes);
  226. };
  227. /**
  228. * @brief Responsible for initialization and de-initialization of an I2C slave peripheral.
  229. */
  230. class I2CSlave : public I2CBus {
  231. public:
  232. /**
  233. * Initialize and install the driver of an I2C slave peripheral.
  234. *
  235. * Initialize and install the bus driver in slave mode. Pullups will be enabled for both pins. If you want a
  236. * different configuration, use configure() and i2c_set_pin() of the underlying driver to disable one or both
  237. * pullups.
  238. *
  239. * @param i2c_number The number of the I2C device.
  240. * @param scl_gpio GPIO number of the SCL line.
  241. * @param sda_gpio GPIO number of the SDA line.
  242. * @param slave_addr The address of the slave device on the I2C bus.
  243. * @param rx_buf_len Receive buffer length.
  244. * @param tx_buf_len Transmit buffer length.
  245. * @param scl_pullup Enable SCL pullup.
  246. * @param sda_pullup Enable SDA pullup.
  247. *
  248. * @throws
  249. */
  250. I2CSlave(i2c_port_t i2c_number,
  251. int scl_gpio,
  252. int sda_gpio,
  253. uint8_t slave_addr,
  254. size_t rx_buf_len,
  255. size_t tx_buf_len,
  256. bool scl_pullup = true,
  257. bool sda_pullup = true);
  258. /**
  259. * Delete the driver.
  260. */
  261. virtual ~I2CSlave();
  262. /**
  263. * Schedule a raw data write once master is ready.
  264. *
  265. * The data is saved in a buffer, waiting for the master to pick it up.
  266. */
  267. virtual int write_raw(const uint8_t* data, size_t data_len, std::chrono::milliseconds timeout);
  268. /**
  269. * Read raw data from the bus.
  270. *
  271. * The data is read directly from the buffer. Hence, it has to be written already by master.
  272. */
  273. virtual int read_raw(uint8_t* buffer, size_t buffer_len, std::chrono::milliseconds timeout);
  274. };
  275. /**
  276. * Implementation for simple I2C writes, which can be executed by \c I2CMaster::transfer().
  277. * It stores the bytes to be written as a vector.
  278. */
  279. class I2CWrite : public I2CTransfer<void> {
  280. public:
  281. /**
  282. * @param bytes The bytes which should be written.
  283. * @param driver_timeout The timeout used for calls like i2c_master_cmd_begin() to the underlying driver.
  284. */
  285. I2CWrite(const std::vector<uint8_t> &bytes, std::chrono::milliseconds driver_timeout = std::chrono::milliseconds(1000));
  286. protected:
  287. /**
  288. * Write the address and set the read bit to 0 to issue the address and request a write.
  289. * Then write the bytes.
  290. *
  291. * @param handle The initialized I2C command handle.
  292. * @param i2c_addr The I2C address of the slave.
  293. */
  294. void queue_cmd(i2c_cmd_handle_t handle, uint8_t i2c_addr) override;
  295. /**
  296. * Set the value of the promise to unblock any callers waiting on it.
  297. */
  298. void process_result() override;
  299. private:
  300. /**
  301. * The bytes to write.
  302. */
  303. std::vector<uint8_t> bytes;
  304. };
  305. /**
  306. * Implementation for simple I2C reads, which can be executed by \c I2CMaster::transfer().
  307. * It stores the bytes to be read as a vector to be returned later via a future.
  308. */
  309. class I2CRead : public I2CTransfer<std::vector<uint8_t> > {
  310. public:
  311. /**
  312. * @param The number of bytes to read.
  313. * @param driver_timeout The timeout used for calls like i2c_master_cmd_begin() to the underlying driver.
  314. */
  315. I2CRead(size_t size, std::chrono::milliseconds driver_timeout = std::chrono::milliseconds(1000));
  316. protected:
  317. /**
  318. * Write the address and set the read bit to 1 to issue the address and request a read.
  319. * Then read into bytes.
  320. *
  321. * @param handle The initialized I2C command handle.
  322. * @param i2c_addr The I2C address of the slave.
  323. */
  324. void queue_cmd(i2c_cmd_handle_t handle, uint8_t i2c_addr) override;
  325. /**
  326. * Set the return value of the promise to unblock any callers waiting on it.
  327. */
  328. std::vector<uint8_t> process_result() override;
  329. private:
  330. /**
  331. * The bytes to read.
  332. */
  333. std::vector<uint8_t> bytes;
  334. };
  335. /**
  336. * This kind of transfer uses repeated start conditions to chain transfers coherently.
  337. * In particular, this can be used to chain multiple single write and read transfers into a single transfer with
  338. * repeated starts as it is commonly done for I2C devices.
  339. * The result is a vector of vectors representing the reads in the order of how they were added using add_read().
  340. */
  341. class I2CComposed : public I2CTransfer<std::vector<std::vector<uint8_t> > > {
  342. public:
  343. I2CComposed(std::chrono::milliseconds driver_timeout = std::chrono::milliseconds(1000));
  344. /**
  345. * Add a read to the chain.
  346. *
  347. * @param size The size of the read in bytes.
  348. */
  349. void add_read(size_t size);
  350. /**
  351. * Add a write to the chain.
  352. *
  353. * @param bytes The bytes to write; size will be bytes.size()
  354. */
  355. void add_write(std::vector<uint8_t> bytes);
  356. protected:
  357. /**
  358. * Write all chained transfers, including a repeated start issue after each but the last transfer.
  359. *
  360. * @param handle The initialized I2C command handle.
  361. * @param i2c_addr The I2C address of the slave.
  362. */
  363. void queue_cmd(i2c_cmd_handle_t handle, uint8_t i2c_addr) override;
  364. /**
  365. * Creates the vector with the vectors from all reads.
  366. */
  367. std::vector<std::vector<uint8_t> > process_result() override;
  368. private:
  369. class CompTransferNode {
  370. public:
  371. virtual ~CompTransferNode() { }
  372. virtual void queue_cmd(i2c_cmd_handle_t handle, uint8_t i2c_addr) = 0;
  373. virtual void process_result(std::vector<std::vector<uint8_t> > &read_results) { }
  374. };
  375. class CompTransferNodeRead : public CompTransferNode {
  376. public:
  377. CompTransferNodeRead(size_t size) : bytes(size) { }
  378. void queue_cmd(i2c_cmd_handle_t handle, uint8_t i2c_addr) override;
  379. void process_result(std::vector<std::vector<uint8_t> > &read_results) override;
  380. private:
  381. std::vector<uint8_t> bytes;
  382. };
  383. class CompTransferNodeWrite : public CompTransferNode {
  384. public:
  385. CompTransferNodeWrite(std::vector<uint8_t> bytes) : bytes(bytes) { }
  386. void queue_cmd(i2c_cmd_handle_t handle, uint8_t i2c_addr) override;
  387. private:
  388. std::vector<uint8_t> bytes;
  389. };
  390. /**
  391. * The chained transfers.
  392. */
  393. std::list<std::shared_ptr<CompTransferNode> > transfer_list;
  394. };
  395. template<typename TReturn>
  396. I2CTransfer<TReturn>::I2CTransfer(std::chrono::milliseconds driver_timeout)
  397. : driver_timeout(driver_timeout.count()) { }
  398. template<typename TReturn>
  399. I2CTransfer<TReturn>::I2CCommandLink::I2CCommandLink()
  400. {
  401. handle = i2c_cmd_link_create();
  402. if (!handle) {
  403. throw I2CException(ESP_ERR_NO_MEM);
  404. }
  405. }
  406. template<typename TReturn>
  407. I2CTransfer<TReturn>::I2CCommandLink::~I2CCommandLink()
  408. {
  409. i2c_cmd_link_delete(handle);
  410. }
  411. template<typename TReturn>
  412. TReturn I2CTransfer<TReturn>::do_transfer(i2c_port_t i2c_num, uint8_t i2c_addr)
  413. {
  414. I2CCommandLink cmd_link;
  415. queue_cmd(cmd_link.handle, i2c_addr);
  416. CHECK_THROW_SPECIFIC(i2c_master_stop(cmd_link.handle), I2CException);
  417. CHECK_THROW_SPECIFIC(i2c_master_cmd_begin(i2c_num, cmd_link.handle, driver_timeout / portTICK_RATE_MS), I2CTransferException);
  418. return process_result();
  419. }
  420. template<typename TransferT>
  421. std::future<typename TransferT::TransferReturnT> I2CMaster::transfer(std::shared_ptr<TransferT> xfer, uint8_t i2c_addr)
  422. {
  423. if (!xfer) throw I2CException(ESP_ERR_INVALID_ARG);
  424. return std::async(std::launch::async, [this](std::shared_ptr<TransferT> xfer, uint8_t i2c_addr) {
  425. return xfer->do_transfer(i2c_num, i2c_addr);
  426. }, xfer, i2c_addr);
  427. }
  428. } // idf