1 /*
2  * Copyright (c) 2023 Würth Elektronik eiSos GmbH & Co. KG
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include "weplatform_i2c.h"
8 
9 #include <errno.h>
10 
11 #ifdef CONFIG_I2C
12 #include <zephyr/drivers/i2c.h>
13 #endif /* CONFIG_I2C */
14 
15 /**
16  * @brief Read data starting from the addressed register via I2C
17  * @param[in] interface Sensor interface
18  * @param[in] regAdr The register address to read from
19  * @param[in] numBytesToRead Number of bytes to read
20  * @param[out] data The read data will be stored here
21  * @retval Error code
22  */
WE_ReadReg_I2C(WE_sensorInterface_t * interface,uint8_t regAdr,uint16_t numBytesToRead,uint8_t * data)23 inline int8_t WE_ReadReg_I2C(WE_sensorInterface_t *interface, uint8_t regAdr,
24 			     uint16_t numBytesToRead, uint8_t *data)
25 {
26 	int status = 0;
27 
28 #ifdef CONFIG_I2C
29 	if (numBytesToRead > 1 && interface->options.i2c.useRegAddrMsbForMultiBytesRead) {
30 		/*
31 		 * Register address most significant bit is used to
32 		 * enable multi bytes read
33 		 */
34 		WRITE_BIT(regAdr, 7, 1);
35 	}
36 	switch(interface->options.i2c.protocol){
37 		case WE_i2cProtocol_RegisterBased:{
38 			status = i2c_burst_read_dt(interface->handle, regAdr, data, numBytesToRead);
39 			break;
40 		}
41 		case WE_i2cProtocol_Raw:{
42 			status = i2c_read_dt(interface->handle, data, numBytesToRead);
43 			break;
44 		}
45 		default:{
46 			status = WE_FAIL;
47 			break;
48 		}
49 	}
50 #else
51 	status = -EIO;
52 #endif /* CONFIG_I2C */
53 
54 	return status == 0 ? WE_SUCCESS : WE_FAIL;
55 }
56 
57 /**
58  * @brief Write data starting from the addressed register via I2C
59  * @param[in] interface Sensor interface
60  * @param[in] regAdr Address of register to be written
61  * @param[in] numBytesToWrite Number of bytes to write
62  * @param[in] data Data to be written
63  * @retval Error code
64  */
WE_WriteReg_I2C(WE_sensorInterface_t * interface,uint8_t regAdr,uint16_t numBytesToWrite,uint8_t * data)65 inline int8_t WE_WriteReg_I2C(WE_sensorInterface_t *interface, uint8_t regAdr,
66 			      uint16_t numBytesToWrite, uint8_t *data)
67 {
68 	int status = 0;
69 
70 #ifdef CONFIG_I2C
71 	switch(interface->options.i2c.protocol){
72 		case WE_i2cProtocol_RegisterBased:{
73 			status = i2c_burst_write_dt(interface->handle, regAdr, data, numBytesToWrite);
74 			break;
75 		}
76 		case WE_i2cProtocol_Raw:{
77 			status = i2c_write_dt(interface->handle, data, numBytesToWrite);
78 			break;
79 		}
80 		default:{
81 			status = WE_FAIL;
82 			break;
83 		}
84 	}
85 #else
86 	status = -EIO;
87 #endif /* CONFIG_I2C */
88 
89 	return status == 0 ? WE_SUCCESS : WE_FAIL;
90 }
91