1 /*
2 * Copyright (c) 2023 Alvaro Garcia Gomez <maxpowel@gmail.com>
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <zephyr/device.h>
8 #include <zephyr/drivers/fuel_gauge.h>
9 #include <zephyr/drivers/i2c.h>
10 #include <zephyr/logging/log.h>
11 #include <zephyr/sys/byteorder.h>
12 #include <zephyr/sys/util.h>
13 #include <zephyr/ztest.h>
14 #include <zephyr/ztest_assert.h>
15
16 struct max17048_fixture {
17 const struct device *dev;
18 const struct fuel_gauge_driver_api *api;
19 };
20
21 void emul_max17048_set_crate_status(int value);
22
max17048_setup(void)23 static void *max17048_setup(void)
24 {
25 static ZTEST_DMEM struct max17048_fixture fixture;
26
27 fixture.dev = DEVICE_DT_GET_ANY(maxim_max17048);
28 k_object_access_all_grant(fixture.dev);
29
30 zassert_true(device_is_ready(fixture.dev), "Fuel Gauge not found");
31
32 return &fixture;
33 }
34
ZTEST_USER_F(max17048,test_get_some_props_failed_returns_bad_status)35 ZTEST_USER_F(max17048, test_get_some_props_failed_returns_bad_status)
36 {
37 fuel_gauge_prop_t prop_types[] = {
38 /* First invalid property */
39 FUEL_GAUGE_PROP_MAX,
40 /* Second invalid property */
41 FUEL_GAUGE_PROP_MAX,
42 /* Valid property */
43 FUEL_GAUGE_VOLTAGE,
44 };
45 union fuel_gauge_prop_val props[ARRAY_SIZE(prop_types)];
46
47 int ret = fuel_gauge_get_props(fixture->dev, prop_types, props, ARRAY_SIZE(props));
48
49 zassert_equal(ret, -ENOTSUP, "Getting bad property has a good status.");
50 }
51
ZTEST_USER_F(max17048,test_get_props__returns_ok)52 ZTEST_USER_F(max17048, test_get_props__returns_ok)
53 {
54 /* Validate what props are supported by the driver */
55
56 fuel_gauge_prop_t prop_types[] = {
57 FUEL_GAUGE_VOLTAGE,
58 FUEL_GAUGE_RUNTIME_TO_EMPTY,
59 FUEL_GAUGE_RUNTIME_TO_FULL,
60 FUEL_GAUGE_RELATIVE_STATE_OF_CHARGE,
61 };
62
63 union fuel_gauge_prop_val props[ARRAY_SIZE(prop_types)];
64
65 zassert_ok(fuel_gauge_get_props(fixture->dev, prop_types, props, ARRAY_SIZE(props)));
66 }
67
ZTEST_USER_F(max17048,test_current_rate_zero)68 ZTEST_USER_F(max17048, test_current_rate_zero)
69 {
70 /* Test when crate is 0, which is a special case */
71
72 fuel_gauge_prop_t prop_types[] = {
73 FUEL_GAUGE_RUNTIME_TO_EMPTY,
74 FUEL_GAUGE_RUNTIME_TO_FULL,
75 };
76 union fuel_gauge_prop_val props[ARRAY_SIZE(prop_types)];
77
78 /** Null value, not charging either discharging. If not handled correctly,
79 * it will cause a division by zero
80 */
81 emul_max17048_set_crate_status(0);
82 int ret = fuel_gauge_get_props(fixture->dev, prop_types, props, ARRAY_SIZE(props));
83
84 zassert_equal(props[0].runtime_to_empty, 0, "Runtime to empty is %d but it should be 0.",
85 props[0].runtime_to_full);
86 zassert_equal(props[1].runtime_to_full, 0, "Runtime to full is %d but it should be 0.",
87 props[1].runtime_to_full);
88
89 zassert_ok(ret);
90 /* Return value to the original state */
91 emul_max17048_set_crate_status(0x4000);
92 }
93
94 ZTEST_SUITE(max17048, NULL, max17048_setup, NULL, NULL, NULL);
95