1 /*
2  * Copyright (c) 2024 Florian Weber <Florian.Weber@live.de>
3  * SPDX-License-Identifier: Apache-2.0
4  */
5 
6 #ifndef ZEPHYR_DRIVERS_SENSOR_MLX90394_MLX90394_H_
7 #define ZEPHYR_DRIVERS_SENSOR_MLX90394_MLX90394_H_
8 
9 #include <zephyr/device.h>
10 #include <zephyr/drivers/i2c.h>
11 #include <zephyr/drivers/sensor.h>
12 #include <zephyr/rtio/rtio.h>
13 
14 #include "mlx90394_reg.h"
15 
16 /*
17  * Time it takes to start-up the device and switch to powerdown mode (after powercycle or soft
18  * reset)
19  */
20 #define MLX90394_STARTUP_TIME_US 400
21 
22 /* Conversion values */
23 #define MLX90394_HIGH_RANGE_MICRO_GAUSS_PER_BIT       INT64_C(15000)
24 #define MLX90394_HIGH_SENSITIVITY_MICRO_GAUSS_PER_BIT INT64_C(1500)
25 #define MLX90394_MICRO_CELSIUS_PER_BIT                INT64_C(20000)
26 
27 /* values for setting SENSOR_ATTR_FULL_SCALE */
28 #define MLX90394_ATTR_FS_HIGH_G INT32_C(500)
29 #define MLX90394_ATTR_FS_LOW_G  INT32_C(50)
30 
31 struct mlx90394_data {
32 	struct __packed {
33 		uint8_t stat1;
34 		uint8_t x_l;
35 		uint8_t x_h;
36 		uint8_t y_l;
37 		uint8_t y_h;
38 		uint8_t z_l;
39 		uint8_t z_h;
40 		uint8_t stat2;
41 		uint8_t temp_l;
42 		uint8_t temp_h;
43 	} sample;
44 	enum sensor_channel channel;
45 	enum mlx90394_reg_config_val config_val;
46 	int32_t measurement_time_us;
47 	struct __packed {
48 		uint8_t ctrl1;
49 		uint8_t ctrl2;
50 		uint8_t ctrl3;
51 		uint8_t ctrl4;
52 	} ctrl_reg_values;
53 	bool initialized;
54 #ifdef CONFIG_SENSOR_ASYNC_API
55 	struct {
56 		struct rtio_iodev_sqe *iodev_sqe;
57 		uint64_t timestamp;
58 		enum mlx90394_reg_config_val config_val;
59 	} work_ctx;
60 	struct k_work_delayable async_fetch_work;
61 	const struct device *dev;
62 #endif
63 };
64 
65 struct mlx90394_config {
66 	struct i2c_dt_spec i2c;
67 };
68 
69 int mlx90394_sample_fetch_internal(const struct device *dev, enum sensor_channel chan);
70 int mlx90394_trigger_measurement_internal(const struct device *dev, enum sensor_channel chan);
71 
72 /* RTIO types and defines */
73 #ifdef CONFIG_SENSOR_ASYNC_API
74 
75 /* shift value to use. */
76 #define MLX90394_SHIFT_MAGN_HIGH_SENSITIVITY (6)
77 #define MLX90394_SHIFT_MAGN_HIGH_RANGE       (9)
78 #define MLX90394_SHIFT_TEMP                  (10)
79 
80 void mlx90394_async_fetch(struct k_work *work);
81 
82 struct mlx90394_decoder_header {
83 	uint64_t timestamp;
84 	enum mlx90394_reg_config_val config_val;
85 };
86 
87 struct mlx90394_encoded_data {
88 	struct mlx90394_decoder_header header;
89 	int16_t readings[4];
90 };
91 
92 int mlx90394_get_decoder(const struct device *dev, const struct sensor_decoder_api **decoder);
93 void mlx90394_submit(const struct device *dev, struct rtio_iodev_sqe *iodev_sqe);
94 #endif
95 
96 #endif /* ZEPHYR_DRIVERS_SENSOR_MLX90394_MLX90394_H_ */
97