1 /*
2  * Copyright 2023 Google LLC
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include "fixture.h"
8 
9 #include <zephyr/drivers/emul_sensor.h>
10 #include <zephyr/drivers/sensor.h>
11 #include <zephyr/ztest.h>
12 
sensor_bmi160_setup_emulator(const struct device * dev,const struct emul * emulator)13 static void sensor_bmi160_setup_emulator(const struct device *dev, const struct emul *emulator)
14 {
15 	static struct {
16 		enum sensor_channel channel;
17 		q31_t value;
18 	} values[] = {
19 		{SENSOR_CHAN_ACCEL_X, 0},       {SENSOR_CHAN_ACCEL_Y, 1 << 28},
20 		{SENSOR_CHAN_ACCEL_Z, 2 << 28}, {SENSOR_CHAN_GYRO_X, 3 << 28},
21 		{SENSOR_CHAN_GYRO_Y, 4 << 28},  {SENSOR_CHAN_GYRO_Z, 5 << 28},
22 	};
23 	static struct sensor_value scale;
24 
25 	/* 4g */
26 	scale.val1 = 39;
27 	scale.val2 = 226600;
28 	zassert_ok(sensor_attr_set(dev, SENSOR_CHAN_ACCEL_XYZ, SENSOR_ATTR_FULL_SCALE, &scale));
29 
30 	/* 125 deg/s */
31 	scale.val1 = 2;
32 	scale.val2 = 181661;
33 	zassert_ok(sensor_attr_set(dev, SENSOR_CHAN_GYRO_XYZ, SENSOR_ATTR_FULL_SCALE, &scale));
34 
35 	for (size_t i = 0; i < ARRAY_SIZE(values); ++i) {
36 		struct sensor_chan_spec chan_spec = {.chan_type = values[i].channel, .chan_idx = 0};
37 
38 		zassert_ok(emul_sensor_backend_set_channel(emulator, chan_spec,
39 							   &values[i].value, 3));
40 	}
41 }
42 
bmi160_setup(void)43 static void *bmi160_setup(void)
44 {
45 	static struct bmi160_fixture fixture = {
46 		.dev_spi = DEVICE_DT_GET(DT_ALIAS(accel_0)),
47 		.dev_i2c = DEVICE_DT_GET(DT_ALIAS(accel_1)),
48 		.emul_spi = EMUL_DT_GET(DT_ALIAS(accel_0)),
49 		.emul_i2c = EMUL_DT_GET(DT_ALIAS(accel_1)),
50 	};
51 
52 	sensor_bmi160_setup_emulator(fixture.dev_i2c, fixture.emul_i2c);
53 	sensor_bmi160_setup_emulator(fixture.dev_spi, fixture.emul_spi);
54 
55 	return &fixture;
56 }
57 
bmi160_before(void * f)58 static void bmi160_before(void *f)
59 {
60 	struct bmi160_fixture *fixture = (struct bmi160_fixture *)f;
61 
62 	zassert_true(device_is_ready(fixture->dev_spi), "'%s' device is not ready",
63 		     fixture->dev_spi->name);
64 	zassert_true(device_is_ready(fixture->dev_i2c), "'%s' device is not ready",
65 		     fixture->dev_i2c->name);
66 
67 	k_object_access_grant(fixture->dev_spi, k_current_get());
68 	k_object_access_grant(fixture->dev_i2c, k_current_get());
69 }
70 
71 ZTEST_SUITE(bmi160, NULL, bmi160_setup, bmi160_before, NULL, NULL);
72