1 /*
2  * Copyright (c) 2023 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/drivers/sensor.h>
11 #include <zephyr/kernel.h>
12 #include <zephyr/logging/log.h>
13 #include <zephyr/sys/util.h>
14 
15 #include "tmd2620.h"
16 
17 LOG_MODULE_DECLARE(TMD2620, CONFIG_SENSOR_LOG_LEVEL);
18 
19 extern struct tmd2620_data tmd2620_driver;
20 
tmd2620_work_cb(struct k_work * work)21 void tmd2620_work_cb(struct k_work *work)
22 {
23 	LOG_DBG("Work callback was called back.");
24 
25 	struct tmd2620_data *data = CONTAINER_OF(work, struct tmd2620_data, work);
26 	const struct device *dev = data->dev;
27 
28 	if (data->p_th_handler != NULL) {
29 		data->p_th_handler(dev, data->p_th_trigger);
30 	}
31 
32 	tmd2620_setup_int(dev->config, true);
33 }
34 
tmd2620_attr_set(const struct device * dev,enum sensor_channel chan,enum sensor_attribute attr,const struct sensor_value * val)35 int tmd2620_attr_set(const struct device *dev, enum sensor_channel chan, enum sensor_attribute attr,
36 		     const struct sensor_value *val)
37 {
38 	LOG_DBG("Setting sensor attributes.");
39 
40 	const struct tmd2620_config *config = dev->config;
41 	int ret;
42 
43 	if (chan != SENSOR_CHAN_PROX) {
44 		return -ENOTSUP;
45 	}
46 
47 	if (attr == SENSOR_ATTR_UPPER_THRESH) {
48 		ret = i2c_reg_write_byte_dt(&config->i2c, TMD2620_PIHT_REG,
49 						(255 - (uint8_t)val->val1));
50 		if (ret < 0) {
51 			return ret;
52 		}
53 	}
54 
55 	if (attr == SENSOR_ATTR_LOWER_THRESH) {
56 		return i2c_reg_write_byte_dt(&config->i2c, TMD2620_PILT_REG, (uint8_t)val->val1);
57 	}
58 
59 	return 0;
60 }
61 
tmd2620_trigger_set(const struct device * dev,const struct sensor_trigger * trigg,sensor_trigger_handler_t handler)62 int tmd2620_trigger_set(const struct device *dev, const struct sensor_trigger *trigg,
63 			sensor_trigger_handler_t handler)
64 {
65 	LOG_DBG("Setting trigger handler.");
66 
67 	const struct tmd2620_config *config = dev->config;
68 	struct tmd2620_data *data = dev->data;
69 	int ret;
70 
71 	tmd2620_setup_int(dev->config, false);
72 
73 	if (trigg->type != SENSOR_TRIG_THRESHOLD) {
74 		return -ENOTSUP;
75 	}
76 
77 	if (trigg->chan != SENSOR_CHAN_PROX) {
78 		return -ENOTSUP;
79 	}
80 
81 	data->p_th_trigger = trigg;
82 	data->p_th_handler = handler;
83 	ret = i2c_reg_update_byte_dt(&config->i2c, TMD2620_INTENAB_REG,
84 				TMD2620_INTENAB_PIEN, TMD2620_INTENAB_PIEN);
85 	if (ret < 0) {
86 		return ret;
87 	}
88 
89 	tmd2620_setup_int(config, true);
90 	if (gpio_pin_get_dt(&config->int_gpio) > 0) {
91 		k_work_submit(&data->work);
92 	}
93 
94 	return 0;
95 }
96