1 /*
2  * Copyright (c) 2024 Gustavo Silva
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #define DT_DRV_COMPAT sciosense_ens160
8 
9 #include <zephyr/drivers/i2c.h>
10 
11 #include "ens160.h"
12 
13 LOG_MODULE_DECLARE(ENS160, CONFIG_SENSOR_LOG_LEVEL);
14 
15 #if DT_ANY_INST_ON_BUS_STATUS_OKAY(i2c)
16 
ens160_read_reg_i2c(const struct device * dev,uint8_t reg,uint8_t * val)17 static int ens160_read_reg_i2c(const struct device *dev, uint8_t reg, uint8_t *val)
18 {
19 	const struct ens160_config *config = dev->config;
20 
21 	return i2c_reg_read_byte_dt(&config->i2c, reg, val);
22 }
23 
ens160_read_data_i2c(const struct device * dev,uint8_t reg,uint8_t * data,size_t len)24 static int ens160_read_data_i2c(const struct device *dev, uint8_t reg, uint8_t *data, size_t len)
25 {
26 	const struct ens160_config *config = dev->config;
27 
28 	return i2c_burst_read_dt(&config->i2c, reg, data, len);
29 }
30 
ens160_write_reg_i2c(const struct device * dev,uint8_t reg,uint8_t val)31 static int ens160_write_reg_i2c(const struct device *dev, uint8_t reg, uint8_t val)
32 {
33 	const struct ens160_config *config = dev->config;
34 
35 	return i2c_reg_write_byte_dt(&config->i2c, reg, val);
36 }
37 
ens160_write_data_i2c(const struct device * dev,uint8_t reg,uint8_t * data,size_t len)38 static int ens160_write_data_i2c(const struct device *dev, uint8_t reg, uint8_t *data, size_t len)
39 {
40 	const struct ens160_config *config = dev->config;
41 
42 	__ASSERT(len == 2, "Only 2 byte write are supported");
43 
44 	uint8_t buff[] = {reg, data[0], data[1]};
45 
46 	return i2c_write_dt(&config->i2c, buff, sizeof(buff));
47 }
48 
49 const struct ens160_transfer_function ens160_i2c_transfer_function = {
50 	.read_reg = ens160_read_reg_i2c,
51 	.read_data = ens160_read_data_i2c,
52 	.write_reg = ens160_write_reg_i2c,
53 	.write_data = ens160_write_data_i2c,
54 };
55 
ens160_i2c_init(const struct device * dev)56 int ens160_i2c_init(const struct device *dev)
57 {
58 	const struct ens160_config *config = dev->config;
59 	struct ens160_data *data = dev->data;
60 
61 	if (!i2c_is_ready_dt(&config->i2c)) {
62 		LOG_DBG("I2C bus device not ready");
63 		return -ENODEV;
64 	}
65 
66 	data->tf = &ens160_i2c_transfer_function;
67 
68 	return 0;
69 }
70 
71 #endif /* DT_ANY_INST_ON_BUS_STATUS_OKAY(i2c) */
72