1 /*
2  * Copyright 2021 The Chromium OS Authors
3  * Copyright 2021 Grinn
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include "ina230.h"
9 
10 #include <zephyr/drivers/sensor.h>
11 #include <zephyr/drivers/gpio.h>
12 #include <zephyr/logging/log.h>
13 
14 LOG_MODULE_DECLARE(INA230, CONFIG_SENSOR_LOG_LEVEL);
15 
ina230_gpio_callback(const struct device * port,struct gpio_callback * cb,uint32_t pin)16 static void ina230_gpio_callback(const struct device *port,
17 				 struct gpio_callback *cb, uint32_t pin)
18 {
19 	struct ina230_data *ina230 = CONTAINER_OF(cb, struct ina230_data, gpio_cb);
20 	const struct device *dev = (const struct device *)ina230->dev;
21 
22 	ARG_UNUSED(port);
23 	ARG_UNUSED(pin);
24 	ARG_UNUSED(cb);
25 
26 	if (ina230->handler_alert) {
27 		ina230->handler_alert(dev, ina230->trig_alert);
28 	}
29 }
30 
ina230_trigger_set(const struct device * dev,const struct sensor_trigger * trig,sensor_trigger_handler_t handler)31 int ina230_trigger_set(const struct device *dev,
32 		       const struct sensor_trigger *trig,
33 		       sensor_trigger_handler_t handler)
34 {
35 	struct ina230_data *ina230 = dev->data;
36 
37 	ARG_UNUSED(trig);
38 
39 	ina230->handler_alert = handler;
40 	ina230->trig_alert = trig;
41 
42 	return 0;
43 }
44 
ina230_trigger_mode_init(const struct device * dev)45 int ina230_trigger_mode_init(const struct device *dev)
46 {
47 	struct ina230_data *ina230 = dev->data;
48 	const struct ina230_config *config = dev->config;
49 	int ret;
50 
51 	/* setup alert gpio interrupt */
52 	if (!gpio_is_ready_dt(&config->alert_gpio)) {
53 		LOG_ERR("Alert GPIO device not ready");
54 		return -ENODEV;
55 	}
56 
57 	ina230->dev = dev;
58 
59 	ret = gpio_pin_configure_dt(&config->alert_gpio, GPIO_INPUT);
60 	if (ret < 0) {
61 		LOG_ERR("Could not configure gpio");
62 		return ret;
63 	}
64 
65 	gpio_init_callback(&ina230->gpio_cb,
66 			   ina230_gpio_callback,
67 			   BIT(config->alert_gpio.pin));
68 
69 	ret = gpio_add_callback(config->alert_gpio.port, &ina230->gpio_cb);
70 	if (ret < 0) {
71 		LOG_ERR("Could not set gpio callback");
72 		return ret;
73 	}
74 
75 	return gpio_pin_interrupt_configure_dt(&config->alert_gpio,
76 					       GPIO_INT_EDGE_BOTH);
77 }
78