1 /*
2  * Copyright 2023 Google LLC
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/drivers/emul.h>
8 #include <zephyr/drivers/emul_sensor.h>
9 #include <zephyr/drivers/i2c_emul.h>
10 #include <zephyr/drivers/sensor.h>
11 #include <zephyr/ztest.h>
12 
13 #include "bmi160.h"
14 #include "checks.h"
15 #include "fixture.h"
16 
17 static int mock_i2c_transfer_fail_reg_number = -1;
18 
mock_i2c_transfer(const struct emul * target,struct i2c_msg * msgs,int num_msgs,int addr)19 static int mock_i2c_transfer(const struct emul *target, struct i2c_msg *msgs, int num_msgs,
20 			     int addr)
21 {
22 	ARG_UNUSED(target);
23 	ARG_UNUSED(addr);
24 	if (mock_i2c_transfer_fail_reg_number >= 0 && i2c_is_read_op(&msgs[1]) &&
25 	    bmi160_i2c_is_touching_reg(msgs, num_msgs, mock_i2c_transfer_fail_reg_number)) {
26 		return -EIO;
27 	}
28 	return -ENOSYS;
29 }
30 
ZTEST_USER_F(bmi160,test_bmi160_i2c_get_offset_fail_to_read_offset_acc)31 ZTEST_USER_F(bmi160, test_bmi160_i2c_get_offset_fail_to_read_offset_acc)
32 {
33 	struct i2c_emul_api mock_bus_api;
34 	struct sensor_value value;
35 
36 	fixture->emul_i2c->bus.i2c->mock_api = &mock_bus_api;
37 	mock_bus_api.transfer = mock_i2c_transfer;
38 
39 	enum sensor_channel channels[] = {SENSOR_CHAN_ACCEL_XYZ, SENSOR_CHAN_GYRO_XYZ};
40 	int fail_registers[] = {BMI160_REG_OFFSET_ACC_X, BMI160_REG_OFFSET_ACC_Y,
41 				BMI160_REG_OFFSET_ACC_Z, BMI160_REG_OFFSET_GYR_X,
42 				BMI160_REG_OFFSET_GYR_Y, BMI160_REG_OFFSET_GYR_Z,
43 				BMI160_REG_OFFSET_EN};
44 
45 	for (int fail_reg_idx = 0; fail_reg_idx < ARRAY_SIZE(fail_registers); ++fail_reg_idx) {
46 		mock_i2c_transfer_fail_reg_number = fail_registers[fail_reg_idx];
47 		for (int chan_idx = 0; chan_idx < ARRAY_SIZE(channels); ++chan_idx) {
48 			zassert_equal(-EIO, sensor_attr_get(fixture->dev_i2c, channels[chan_idx],
49 							    SENSOR_ATTR_OFFSET, &value));
50 		}
51 	}
52 }
53