1 /*
2  * Copyright (c) 2018 Phytec Messtechnik GmbH
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/device.h>
8 #include <zephyr/drivers/gpio.h>
9 #include <zephyr/drivers/i2c.h>
10 #include <zephyr/sys/util.h>
11 #include <zephyr/kernel.h>
12 #include <zephyr/drivers/sensor.h>
13 #include "apds9960.h"
14 
15 extern struct apds9960_data apds9960_driver;
16 
17 #include <zephyr/logging/log.h>
18 LOG_MODULE_DECLARE(APDS9960, CONFIG_SENSOR_LOG_LEVEL);
19 
apds9960_work_cb(struct k_work * work)20 void apds9960_work_cb(struct k_work *work)
21 {
22 	struct apds9960_data *data = CONTAINER_OF(work,
23 						  struct apds9960_data,
24 						  work);
25 	const struct device *dev = data->dev;
26 
27 	if (data->p_th_handler != NULL) {
28 		data->p_th_handler(dev, data->p_th_trigger);
29 	}
30 
31 	apds9960_setup_int(dev->config, true);
32 }
33 
apds9960_attr_set(const struct device * dev,enum sensor_channel chan,enum sensor_attribute attr,const struct sensor_value * val)34 int apds9960_attr_set(const struct device *dev,
35 		      enum sensor_channel chan,
36 		      enum sensor_attribute attr,
37 		      const struct sensor_value *val)
38 {
39 	const struct apds9960_config *config = dev->config;
40 
41 	if (chan == SENSOR_CHAN_PROX) {
42 		if (attr == SENSOR_ATTR_UPPER_THRESH) {
43 			if (i2c_reg_write_byte_dt(&config->i2c,
44 						  APDS9960_PIHT_REG,
45 						  (uint8_t)val->val1)) {
46 				return -EIO;
47 			}
48 
49 			return 0;
50 		}
51 		if (attr == SENSOR_ATTR_LOWER_THRESH) {
52 			if (i2c_reg_write_byte_dt(&config->i2c,
53 						  APDS9960_PILT_REG,
54 						  (uint8_t)val->val1)) {
55 				return -EIO;
56 			}
57 
58 			return 0;
59 		}
60 	}
61 
62 	return -ENOTSUP;
63 }
64 
apds9960_trigger_set(const struct device * dev,const struct sensor_trigger * trig,sensor_trigger_handler_t handler)65 int apds9960_trigger_set(const struct device *dev,
66 			 const struct sensor_trigger *trig,
67 			 sensor_trigger_handler_t handler)
68 {
69 	const struct apds9960_config *config = dev->config;
70 	struct apds9960_data *data = dev->data;
71 
72 	apds9960_setup_int(dev->config, false);
73 
74 	switch (trig->type) {
75 	case SENSOR_TRIG_THRESHOLD:
76 		if (trig->chan == SENSOR_CHAN_PROX) {
77 			data->p_th_handler = handler;
78 			data->p_th_trigger = trig;
79 			if (i2c_reg_update_byte_dt(&config->i2c,
80 						   APDS9960_ENABLE_REG,
81 						   APDS9960_ENABLE_PIEN,
82 						   APDS9960_ENABLE_PIEN)) {
83 				return -EIO;
84 			}
85 		} else {
86 			return -ENOTSUP;
87 		}
88 		break;
89 	default:
90 		LOG_ERR("Unsupported sensor trigger");
91 		return -ENOTSUP;
92 	}
93 
94 	apds9960_setup_int(config, true);
95 	if (gpio_pin_get_dt(&config->int_gpio) > 0) {
96 		k_work_submit(&data->work);
97 	}
98 
99 	return 0;
100 }
101