1 /*
2  * Copyright (c) 2024 Kickmaker
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/device.h>
8 #include <zephyr/drivers/pwm.h>
9 #include <zephyr/drivers/pwm/pwm_fake.h>
10 #include <zephyr/fff.h>
11 #include <zephyr/sys/util.h>
12 
13 #ifdef CONFIG_ZTEST
14 #include <zephyr/ztest.h>
15 #endif /* CONFIG_ZTEST */
16 
17 #define DT_DRV_COMPAT zephyr_fake_pwm
18 
19 /** Fake PWM config structure */
20 struct fake_pwm_config {
21 	/** Frequency of the (fake) underlying timer */
22 	uint64_t frequency_hz;
23 };
24 
25 DEFINE_FAKE_VALUE_FUNC(int, fake_pwm_set_cycles, const struct device *, uint32_t, uint32_t,
26 		       uint32_t, pwm_flags_t);
27 
28 #ifdef CONFIG_ZTEST
fake_pwm_reset_rule_before(const struct ztest_unit_test * test,void * fixture)29 static void fake_pwm_reset_rule_before(const struct ztest_unit_test *test, void *fixture)
30 {
31 	ARG_UNUSED(test);
32 	ARG_UNUSED(fixture);
33 
34 	RESET_FAKE(fake_pwm_set_cycles);
35 }
36 
37 ZTEST_RULE(fake_pwm_reset_rule, fake_pwm_reset_rule_before, NULL);
38 #endif /* CONFIG_ZTEST */
39 
fake_pwm_get_cycles_per_sec(const struct device * dev,uint32_t channel,uint64_t * cycles)40 static int fake_pwm_get_cycles_per_sec(const struct device *dev, uint32_t channel, uint64_t *cycles)
41 {
42 	ARG_UNUSED(channel);
43 	const struct fake_pwm_config *config = dev->config;
44 
45 	*cycles = config->frequency_hz;
46 
47 	return 0;
48 }
49 
50 static DEVICE_API(pwm, fake_pwm_driver_api) = {
51 	.set_cycles = fake_pwm_set_cycles,
52 	.get_cycles_per_sec = fake_pwm_get_cycles_per_sec,
53 };
54 
55 #define FAKE_PWM_INIT(inst)                                                                        \
56 	static const struct fake_pwm_config fake_pwm_config_##inst = {                             \
57 		.frequency_hz = DT_INST_PROP(inst, frequency),                                     \
58 	};                                                                                         \
59                                                                                                    \
60 	DEVICE_DT_INST_DEFINE(inst, NULL, NULL, NULL, &fake_pwm_config_##inst, POST_KERNEL,        \
61 			      CONFIG_PWM_INIT_PRIORITY, &fake_pwm_driver_api);
62 
63 DT_INST_FOREACH_STATUS_OKAY(FAKE_PWM_INIT)
64