1 /*
2  * Copyright (c) 2024 Arif Balik <arifbalik@outlook.com>
3  * SPDX-License-Identifier: Apache-2.0
4  */
5 
6 #include <soc.h>
7 #include <stdlib.h>
8 #include <stdbool.h>
9 #include <autoconf.h>
10 #include <zephyr/irq.h>
11 #include <zephyr/kernel.h>
12 #include <zephyr/device.h>
13 #include <zephyr/devicetree.h>
14 #include <zephyr/input/input.h>
15 #include <zephyr/drivers/reset.h>
16 #include <zephyr/sys/util.h>
17 #include <zephyr/logging/log.h>
18 #include <zephyr/sys/ring_buffer.h>
19 #include <zephyr/drivers/pinctrl.h>
20 #include <zephyr/drivers/clock_control/stm32_clock_control.h>
21 
22 LOG_MODULE_REGISTER(tsc_keys, CONFIG_INPUT_LOG_LEVEL);
23 
24 #define DT_DRV_COMPAT st_stm32_tsc
25 
26 /* each group only has 4 configurable I/O */
27 #define GET_GROUP_BITS(val, group) (uint32_t)(((val) & 0x0f) << ((group - 1) * 4))
28 
29 struct stm32_tsc_group_config {
30 	uint8_t group;
31 	uint8_t channel_ios;
32 	uint8_t sampling_io;
33 	bool use_as_shield;
34 };
35 
36 typedef void (*stm32_tsc_group_ready_cb)(uint32_t count_value, void *user_data);
37 
38 struct stm32_tsc_group_data {
39 	stm32_tsc_group_ready_cb cb;
40 	void *user_data;
41 };
42 
43 struct stm32_tsc_config {
44 	const TSC_TypeDef *tsc;
45 	const struct stm32_pclken *pclken;
46 	struct reset_dt_spec reset;
47 	const struct pinctrl_dev_config *pcfg;
48 	const struct stm32_tsc_group_config *group_config;
49 	struct stm32_tsc_group_data *group_data;
50 	uint8_t group_cnt;
51 
52 	uint32_t pgpsc;
53 	uint8_t ctph;
54 	uint8_t ctpl;
55 	bool spread_spectrum;
56 	uint8_t sscpsc;
57 	uint8_t ssd;
58 	uint16_t max_count;
59 	bool iodef;
60 	bool sync_acq;
61 	bool sync_pol;
62 	void (*irq_func)(void);
63 };
64 
stm32_tsc_group_register_callback(const struct device * dev,uint8_t group_idx,stm32_tsc_group_ready_cb cb,void * user_data)65 int stm32_tsc_group_register_callback(const struct device *dev, uint8_t group_idx,
66 				      stm32_tsc_group_ready_cb cb, void *user_data)
67 {
68 	const struct stm32_tsc_config *config = dev->config;
69 
70 	if (group_idx >= config->group_cnt) {
71 		LOG_ERR("%s: group index %d is out of range", dev->name, group_idx);
72 		return -EINVAL;
73 	}
74 
75 	struct stm32_tsc_group_data *group_data = &config->group_data[group_idx];
76 
77 	group_data->cb = cb;
78 	group_data->user_data = user_data;
79 
80 	return 0;
81 }
82 
stm32_tsc_start(const struct device * dev)83 void stm32_tsc_start(const struct device *dev)
84 {
85 	const struct stm32_tsc_config *config = dev->config;
86 
87 	/* clear interrupts */
88 	sys_set_bits((mem_addr_t)&config->tsc->ICR, TSC_ICR_EOAIC | TSC_ICR_MCEIC);
89 
90 	/* enable end of acquisition and max count error interrupts */
91 	sys_set_bits((mem_addr_t)&config->tsc->IER, TSC_IER_EOAIE | TSC_IER_MCEIE);
92 
93 	/* TODO: When sync acqusition mode is enabled, both this bit and an external input signal
94 	 * should be set. When the acqusition stops this bit is cleared, so even if a sync signal is
95 	 * present, the next acqusition will not start until this bit is set again.
96 	 */
97 	/* start acquisition */
98 	sys_set_bit((mem_addr_t)&config->tsc->CR, TSC_CR_START_Pos);
99 }
100 
get_group_index(const struct device * dev,uint8_t group,uint8_t * group_idx)101 static int get_group_index(const struct device *dev, uint8_t group, uint8_t *group_idx)
102 {
103 	const struct stm32_tsc_config *config = dev->config;
104 	const struct stm32_tsc_group_config *groups = config->group_config;
105 
106 	for (int i = 0; i < config->group_cnt; i++) {
107 		if (groups[i].group == group) {
108 			*group_idx = i;
109 			return 0;
110 		}
111 	}
112 
113 	return -ENODEV;
114 }
115 
stm32_tsc_handle_incoming_data(const struct device * dev)116 static int stm32_tsc_handle_incoming_data(const struct device *dev)
117 {
118 	const struct stm32_tsc_config *config = dev->config;
119 
120 	if (sys_test_bit((mem_addr_t)&config->tsc->ISR, TSC_ISR_MCEF_Pos)) {
121 		/* clear max count error flag */
122 		sys_set_bit((mem_addr_t)&config->tsc->ICR, TSC_ICR_MCEIC_Pos);
123 		LOG_ERR("%s: max count error", dev->name);
124 		LOG_HEXDUMP_DBG(config->tsc, sizeof(TSC_TypeDef), "TSC Registers");
125 		return -EIO;
126 	}
127 
128 	if (sys_test_bit((mem_addr_t)&config->tsc->ISR, TSC_ISR_EOAF_Pos)) {
129 		/* clear end of acquisition flag */
130 		sys_set_bit((mem_addr_t)&config->tsc->ICR, TSC_ICR_EOAIC_Pos);
131 
132 		/* read values */
133 		for (uint8_t i = 0; i < config->group_cnt; i++) {
134 			const struct stm32_tsc_group_config *group = &config->group_config[i];
135 			uint32_t group_bit = BIT(group->group - 1) << 16;
136 
137 			if (config->tsc->IOGCSR & group_bit) {
138 				uint32_t count_value = sys_read32(
139 					(mem_addr_t)&config->tsc->IOGXCR[group->group - 1]);
140 
141 				uint8_t group_idx = 0;
142 
143 				int ret = get_group_index(dev, group->group, &group_idx);
144 
145 				if (ret < 0) {
146 					LOG_ERR("%s: group %d not found", dev->name, group->group);
147 					return ret;
148 				}
149 
150 				struct stm32_tsc_group_data *data = &config->group_data[group_idx];
151 
152 				if (data->cb) {
153 					data->cb(count_value, data->user_data);
154 				}
155 			}
156 		}
157 	}
158 
159 	return 0;
160 }
161 
stm32_tsc_isr(const struct device * dev)162 static void stm32_tsc_isr(const struct device *dev)
163 {
164 	const struct stm32_tsc_config *config = dev->config;
165 
166 	/* disable interrupts */
167 	sys_clear_bits((mem_addr_t)&config->tsc->IER, TSC_IER_EOAIE | TSC_IER_MCEIE);
168 
169 	stm32_tsc_handle_incoming_data(dev);
170 }
171 
stm32_tsc_init(const struct device * dev)172 static int stm32_tsc_init(const struct device *dev)
173 {
174 	const struct stm32_tsc_config *config = dev->config;
175 	const struct device *const clk = DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE);
176 
177 	int ret;
178 
179 	if (!device_is_ready(clk)) {
180 		LOG_ERR("%s: clock controller device not ready", dev->name);
181 		return -ENODEV;
182 	}
183 
184 	/* reset TSC values to default */
185 	ret = reset_line_toggle_dt(&config->reset);
186 	if (ret < 0) {
187 		LOG_ERR("Failed to reset %s (%d)", dev->name, ret);
188 		return ret;
189 	}
190 
191 	ret = clock_control_on(clk, (clock_control_subsys_t)&config->pclken[0]);
192 	if (ret < 0) {
193 		LOG_ERR("Failed to enable clock for %s (%d)", dev->name, ret);
194 		return ret;
195 	}
196 
197 	ret = pinctrl_apply_state(config->pcfg, PINCTRL_STATE_DEFAULT);
198 	if (ret < 0) {
199 		LOG_ERR("Failed to configure %s pins (%d)", dev->name, ret);
200 		return ret;
201 	}
202 
203 	/* set ctph (bits 31:28) and ctpl (bits 27:24) */
204 	sys_set_bits((mem_addr_t)&config->tsc->CR, (((config->ctph - 1) << 4) | (config->ctpl - 1))
205 							   << TSC_CR_CTPL_Pos);
206 
207 	/* set spread spectrum deviation (bits 23:17) */
208 	sys_set_bits((mem_addr_t)&config->tsc->CR, config->ssd << TSC_CR_SSD_Pos);
209 
210 	/* set pulse generator prescaler (bits 14:12) */
211 	sys_set_bits((mem_addr_t)&config->tsc->CR, config->pgpsc << TSC_CR_PGPSC_Pos);
212 
213 	/* set max count value (bits 7:5) */
214 	sys_set_bits((mem_addr_t)&config->tsc->CR, config->max_count << TSC_CR_MCV_Pos);
215 
216 	/* set spread spectrum prescaler (bit 15) */
217 	if (config->sscpsc == 2) {
218 		sys_set_bit((mem_addr_t)&config->tsc->CR, TSC_CR_SSPSC_Pos);
219 	}
220 
221 	/* set sync bit polarity */
222 	if (config->sync_pol) {
223 		sys_set_bit((mem_addr_t)&config->tsc->CR, TSC_CR_SYNCPOL_Pos);
224 	}
225 
226 	/* set sync acquisition */
227 	if (config->sync_acq) {
228 		sys_set_bit((mem_addr_t)&config->tsc->CR, TSC_CR_AM_Pos);
229 	}
230 
231 	/* set I/O default mode */
232 	if (config->iodef) {
233 		sys_set_bit((mem_addr_t)&config->tsc->CR, TSC_CR_IODEF_Pos);
234 	}
235 
236 	/* set spread spectrum */
237 	if (config->spread_spectrum) {
238 		sys_set_bit((mem_addr_t)&config->tsc->CR, TSC_CR_SSE_Pos);
239 	}
240 
241 	/* group configuration */
242 	for (int i = 0; i < config->group_cnt; i++) {
243 		const struct stm32_tsc_group_config *group = &config->group_config[i];
244 
245 		if (group->channel_ios & group->sampling_io) {
246 			LOG_ERR("%s: group %d has the same channel and sampling I/O", dev->name,
247 				group->group);
248 			return -EINVAL;
249 		}
250 
251 		/* if use_as_shield is true, the channel I/Os are used as shield, and can only have
252 		 * values 1,2,4,8
253 		 */
254 		if (group->use_as_shield && group->channel_ios != 1 && group->channel_ios != 2 &&
255 		    group->channel_ios != 4 && group->channel_ios != 8) {
256 			LOG_ERR("%s: group %d is used as shield, but has invalid channel I/Os. "
257 				"Can only have one",
258 				dev->name, group->group);
259 			return -EINVAL;
260 		}
261 
262 		/* clear schmitt trigger hysteresis for enabled I/Os */
263 		sys_clear_bits(
264 			(mem_addr_t)&config->tsc->IOHCR,
265 			GET_GROUP_BITS(group->channel_ios | group->sampling_io, group->group));
266 
267 		/* set channel I/Os */
268 		sys_set_bits((mem_addr_t)&config->tsc->IOCCR,
269 			     GET_GROUP_BITS(group->channel_ios, group->group));
270 
271 		/* set sampling I/O */
272 		sys_set_bits((mem_addr_t)&config->tsc->IOSCR,
273 			     GET_GROUP_BITS(group->sampling_io, group->group));
274 
275 		/* enable group */
276 		if (!group->use_as_shield) {
277 			sys_set_bit((mem_addr_t)&config->tsc->IOGCSR, group->group - 1);
278 		}
279 	}
280 
281 	/* disable interrupts */
282 	sys_clear_bits((mem_addr_t)&config->tsc->IER, TSC_IER_EOAIE | TSC_IER_MCEIE);
283 
284 	/* clear interrupts */
285 	sys_set_bits((mem_addr_t)&config->tsc->ICR, TSC_ICR_EOAIC | TSC_ICR_MCEIC);
286 
287 	/* enable peripheral */
288 	sys_set_bit((mem_addr_t)&config->tsc->CR, TSC_CR_TSCE_Pos);
289 
290 	config->irq_func();
291 
292 	return 0;
293 }
294 
295 #define STM32_TSC_GROUP_DEFINE(node_id)                                                            \
296 	{                                                                                          \
297 		.group = DT_PROP(node_id, group),                                                  \
298 		.channel_ios = DT_PROP(node_id, channel_ios),                                      \
299 		.sampling_io = DT_PROP(node_id, sampling_io),                                      \
300 		.use_as_shield = DT_PROP(node_id, st_use_as_shield),                               \
301 	}
302 
303 #define STM32_TSC_INIT(index)                                                                      \
304 	static const struct stm32_pclken pclken_##index[] = STM32_DT_INST_CLOCKS(index);           \
305                                                                                                    \
306 	PINCTRL_DT_INST_DEFINE(index);                                                             \
307                                                                                                    \
308 	static void stm32_tsc_irq_init_##index(void)                                               \
309 	{                                                                                          \
310 		IRQ_CONNECT(DT_INST_IRQN(index), DT_INST_IRQ(index, priority), stm32_tsc_isr,      \
311 			    DEVICE_DT_INST_GET(index), 0);                                         \
312 		irq_enable(DT_INST_IRQN(index));                                                   \
313 	};                                                                                         \
314                                                                                                    \
315 	static const struct stm32_tsc_group_config group_config_cfg_##index[] = {                  \
316 		DT_INST_FOREACH_CHILD_STATUS_OKAY_SEP(index, STM32_TSC_GROUP_DEFINE, (,))};        \
317                                                                                                    \
318 	static struct stm32_tsc_group_data                                                         \
319 		group_data_cfg_##index[DT_INST_CHILD_NUM_STATUS_OKAY(index)];                      \
320                                                                                                    \
321 	static const struct stm32_tsc_config stm32_tsc_cfg_##index = {                             \
322 		.tsc = (TSC_TypeDef *)DT_INST_REG_ADDR(index),                                     \
323 		.pclken = pclken_##index,                                                          \
324 		.reset = RESET_DT_SPEC_INST_GET(index),                                            \
325 		.pcfg = PINCTRL_DT_INST_DEV_CONFIG_GET(index),                                     \
326 		.group_config = group_config_cfg_##index,                                          \
327 		.group_data = group_data_cfg_##index,                                              \
328 		.group_cnt = DT_INST_CHILD_NUM_STATUS_OKAY(index),                                 \
329 		.pgpsc = LOG2CEIL(DT_INST_PROP(index, st_pulse_generator_prescaler)),              \
330 		.ctph = DT_INST_PROP(index, st_charge_transfer_pulse_high),                        \
331 		.ctpl = DT_INST_PROP(index, st_charge_transfer_pulse_low),                         \
332 		.spread_spectrum = DT_INST_PROP(index, st_spread_spectrum),                        \
333 		.sscpsc = DT_INST_PROP(index, st_spread_spectrum_prescaler),                       \
334 		.ssd = DT_INST_PROP(index, st_spread_spectrum_deviation),                          \
335 		.max_count = LOG2CEIL(DT_INST_PROP(index, st_max_count_value) + 1) - 8,            \
336 		.iodef = DT_INST_PROP(index, st_iodef_float),                                      \
337 		.sync_acq = DT_INST_PROP(index, st_synced_acquisition),                            \
338 		.sync_pol = DT_INST_PROP(index, st_syncpol_rising),                                \
339 		.irq_func = stm32_tsc_irq_init_##index,                                            \
340 	};                                                                                         \
341 	DEVICE_DT_INST_DEFINE(index, stm32_tsc_init, NULL, NULL, &stm32_tsc_cfg_##index,           \
342 			      POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEFAULT, NULL);
343 
344 DT_INST_FOREACH_STATUS_OKAY(STM32_TSC_INIT)
345 
346 struct input_tsc_keys_data {
347 	uint32_t buffer[CONFIG_INPUT_STM32_TSC_KEYS_BUFFER_WORD_SIZE];
348 	struct ring_buf rb;
349 	bool expect_release;
350 	struct k_timer sampling_timer;
351 };
352 
353 struct input_tsc_keys_config {
354 	const struct device *tsc_dev;
355 	uint32_t sampling_interval_ms;
356 	int32_t noise_threshold;
357 	int zephyr_code;
358 	uint8_t group;
359 };
360 
input_tsc_sampling_timer_callback(struct k_timer * timer)361 static void input_tsc_sampling_timer_callback(struct k_timer *timer)
362 {
363 	const struct device *dev = k_timer_user_data_get(timer);
364 
365 	stm32_tsc_start(dev);
366 }
367 
input_tsc_callback_handler(uint32_t count_value,void * user_data)368 static void input_tsc_callback_handler(uint32_t count_value, void *user_data)
369 {
370 	const struct device *dev = (const struct device *)user_data;
371 	const struct input_tsc_keys_config *config =
372 		(const struct input_tsc_keys_config *)dev->config;
373 	struct input_tsc_keys_data *data = (struct input_tsc_keys_data *)dev->data;
374 
375 	if (ring_buf_item_space_get(&data->rb) == 0) {
376 		uint32_t oldest_point;
377 		int32_t slope;
378 
379 		(void)ring_buf_get(&data->rb, (uint8_t *)&oldest_point, sizeof(oldest_point));
380 
381 		slope = count_value - oldest_point;
382 		if (slope < -config->noise_threshold && !data->expect_release) {
383 			data->expect_release = true;
384 			input_report_key(dev, config->zephyr_code, 1, false, K_NO_WAIT);
385 		} else if (slope > config->noise_threshold && data->expect_release) {
386 			data->expect_release = false;
387 			input_report_key(dev, config->zephyr_code, 0, false, K_NO_WAIT);
388 		}
389 	}
390 
391 	(void)ring_buf_put(&data->rb, (uint8_t *)&count_value, sizeof(count_value));
392 }
393 
input_tsc_keys_init(const struct device * dev)394 static int input_tsc_keys_init(const struct device *dev)
395 {
396 	const struct input_tsc_keys_config *config = dev->config;
397 	struct input_tsc_keys_data *data = dev->data;
398 
399 	if (!device_is_ready(config->tsc_dev)) {
400 		LOG_ERR("%s: TSC device not ready", config->tsc_dev->name);
401 		return -ENODEV;
402 	}
403 
404 	ring_buf_item_init(&data->rb, CONFIG_INPUT_STM32_TSC_KEYS_BUFFER_WORD_SIZE, data->buffer);
405 
406 	uint8_t group_index = 0;
407 
408 	int ret = get_group_index(config->tsc_dev, config->group, &group_index);
409 
410 	if (ret) {
411 		LOG_ERR("%s: group %d not found", config->tsc_dev->name, config->group);
412 		return ret;
413 	}
414 
415 	ret = stm32_tsc_group_register_callback(config->tsc_dev, group_index,
416 						input_tsc_callback_handler, (void *)dev);
417 
418 	if (ret) {
419 		LOG_ERR("%s: failed to register callback for group %d", config->tsc_dev->name,
420 			config->group);
421 		return ret;
422 	}
423 
424 	k_timer_init(&data->sampling_timer, input_tsc_sampling_timer_callback, NULL);
425 	k_timer_user_data_set(&data->sampling_timer, (void *)config->tsc_dev);
426 	k_timer_start(&data->sampling_timer, K_NO_WAIT, K_MSEC(config->sampling_interval_ms));
427 
428 	return 0;
429 }
430 
431 #define TSC_KEYS_INIT(inst)                                                                        \
432                                                                                                    \
433 	static struct input_tsc_keys_data tsc_keys_data_##inst;                                    \
434                                                                                                    \
435 	static const struct input_tsc_keys_config tsc_keys_config_##inst = {                       \
436 		.tsc_dev = DEVICE_DT_GET(DT_GPARENT(inst)),                                        \
437 		.sampling_interval_ms = DT_PROP(inst, sampling_interval_ms),                       \
438 		.zephyr_code = DT_PROP(inst, zephyr_code),                                         \
439 		.noise_threshold = DT_PROP(inst, noise_threshold),                                 \
440 		.group = DT_PROP(DT_PARENT(inst), group),                                          \
441 	};                                                                                         \
442                                                                                                    \
443 	DEVICE_DT_DEFINE(inst, input_tsc_keys_init, NULL, &tsc_keys_data_##inst,                   \
444 			 &tsc_keys_config_##inst, POST_KERNEL, CONFIG_INPUT_INIT_PRIORITY, NULL);
445 
446 DT_FOREACH_STATUS_OKAY(tsc_keys, TSC_KEYS_INIT);
447