1 /**
2  * @file
3  *
4  * @brief Emulated ADC driver
5  */
6 
7 /*
8  * Copyright 2021 Google LLC
9  *
10  * SPDX-License-Identifier: Apache-2.0
11  */
12 
13 #define DT_DRV_COMPAT zephyr_adc_emul
14 
15 #include <drivers/adc.h>
16 #include <drivers/adc/adc_emul.h>
17 #include <kernel.h>
18 #include <logging/log.h>
19 #include <sys/byteorder.h>
20 #include <sys/util.h>
21 #include <zephyr.h>
22 
23 LOG_MODULE_REGISTER(adc_emul, CONFIG_ADC_LOG_LEVEL);
24 
25 #define ADC_CONTEXT_USES_KERNEL_TIMER
26 #include "adc_context.h"
27 
28 #define ADC_EMUL_MAX_RESOLUTION 16
29 
30 typedef uint16_t adc_emul_res_t;
31 
32 enum adc_emul_input_source {
33 	ADC_EMUL_CONST_VALUE,
34 	ADC_EMUL_CUSTOM_FUNC,
35 };
36 
37 /**
38  * @brief Channel of emulated ADC config
39  *
40  * This structure contains configuration of one channel of emualted ADC.
41  */
42 struct adc_emul_chan_cfg {
43 	/** Pointer to function used to obtain input mV */
44 	adc_emul_value_func func;
45 	/** Pointer to data that are passed to @a func on call */
46 	void *func_data;
47 	/** Constant mV input value */
48 	uint32_t const_value;
49 	/** Gain used on output value */
50 	enum adc_gain gain;
51 	/** Reference source */
52 	enum adc_reference ref;
53 	/** Input source which is used to obtain input value */
54 	enum adc_emul_input_source input;
55 };
56 
57 /**
58  * @brief Emulated ADC config
59  *
60  * This structure contains constant data for given instance of emulated ADC.
61  */
62 struct adc_emul_config {
63 	/** Number of supported channels */
64 	uint8_t num_channels;
65 };
66 
67 /**
68  * @brief Emulated ADC data
69  *
70  * This structure contains data structures used by a emulated ADC.
71  */
72 struct adc_emul_data {
73 	/** Structure that handle state of ongoing read operation */
74 	struct adc_context ctx;
75 	/** Pointer to ADC emulator own device structure */
76 	const struct device *dev;
77 	/** Pointer to memory where next sample will be written */
78 	uint16_t *buf;
79 	/** Pointer to where will be data stored in case of repeated sampling */
80 	uint16_t *repeat_buf;
81 	/** Mask with channels that will be sampled */
82 	uint32_t channels;
83 	/** Mask created from requested resolution in read operation */
84 	uint16_t res_mask;
85 	/** Reference voltage for ADC_REF_VDD_1 source */
86 	uint16_t ref_vdd;
87 	/** Reference voltage for ADC_REF_EXTERNAL0 source */
88 	uint16_t ref_ext0;
89 	/** Reference voltage for ADC_REF_EXTERNAL1 source */
90 	uint16_t ref_ext1;
91 	/** Reference voltage for ADC_REF_INTERNAL source */
92 	uint16_t ref_int;
93 	/** Array of each channel configuration */
94 	struct adc_emul_chan_cfg *chan_cfg;
95 	/** Structure used for acquisition thread */
96 	struct k_thread thread;
97 	/** Semaphore used to control acquisiton thread */
98 	struct k_sem sem;
99 	/** Mutex used to control access to channels config and ref voltages */
100 	struct k_mutex cfg_mtx;
101 
102 	/** Stack for acquisition thread */
103 	K_KERNEL_STACK_MEMBER(stack,
104 			CONFIG_ADC_EMUL_ACQUISITION_THREAD_STACK_SIZE);
105 };
106 
adc_emul_const_value_set(const struct device * dev,unsigned int chan,uint32_t value)107 int adc_emul_const_value_set(const struct device *dev, unsigned int chan,
108 			     uint32_t value)
109 {
110 	const struct adc_emul_config *config = dev->config;
111 	struct adc_emul_data *data = dev->data;
112 	struct adc_emul_chan_cfg *chan_cfg;
113 
114 	if (chan >= config->num_channels) {
115 		LOG_ERR("unsupported channel %d", chan);
116 		return -EINVAL;
117 	}
118 
119 	chan_cfg = &data->chan_cfg[chan];
120 
121 	k_mutex_lock(&data->cfg_mtx, K_FOREVER);
122 
123 	chan_cfg->input = ADC_EMUL_CONST_VALUE;
124 	chan_cfg->const_value = value;
125 
126 	k_mutex_unlock(&data->cfg_mtx);
127 
128 	return 0;
129 }
130 
adc_emul_value_func_set(const struct device * dev,unsigned int chan,adc_emul_value_func func,void * func_data)131 int adc_emul_value_func_set(const struct device *dev, unsigned int chan,
132 			    adc_emul_value_func func, void *func_data)
133 {
134 	const struct adc_emul_config *config = dev->config;
135 	struct adc_emul_data *data = dev->data;
136 	struct adc_emul_chan_cfg *chan_cfg;
137 
138 	if (chan >= config->num_channels) {
139 		LOG_ERR("unsupported channel %d", chan);
140 		return -EINVAL;
141 	}
142 
143 	chan_cfg = &data->chan_cfg[chan];
144 
145 	k_mutex_lock(&data->cfg_mtx, K_FOREVER);
146 
147 	chan_cfg->func = func;
148 	chan_cfg->func_data = func_data;
149 	chan_cfg->input = ADC_EMUL_CUSTOM_FUNC;
150 
151 	k_mutex_unlock(&data->cfg_mtx);
152 
153 	return 0;
154 }
155 
adc_emul_ref_voltage_set(const struct device * dev,enum adc_reference ref,uint16_t value)156 int adc_emul_ref_voltage_set(const struct device *dev, enum adc_reference ref,
157 			     uint16_t value)
158 {
159 	struct adc_driver_api *api = (struct adc_driver_api *)dev->api;
160 	struct adc_emul_data *data = dev->data;
161 	int err = 0;
162 
163 	k_mutex_lock(&data->cfg_mtx, K_FOREVER);
164 
165 	switch (ref) {
166 	case ADC_REF_VDD_1:
167 		data->ref_vdd = value;
168 		break;
169 	case ADC_REF_INTERNAL:
170 		data->ref_int = value;
171 		api->ref_internal = value;
172 		break;
173 	case ADC_REF_EXTERNAL0:
174 		data->ref_ext0 = value;
175 		break;
176 	case ADC_REF_EXTERNAL1:
177 		data->ref_ext1 = value;
178 		break;
179 	default:
180 		err = -EINVAL;
181 	}
182 
183 	k_mutex_unlock(&data->cfg_mtx);
184 
185 	return err;
186 }
187 
188 /**
189  * @brief Convert @p ref to reference voltage value in mV
190  *
191  * @param data Internal data of ADC emulator
192  * @param ref Select which reference source should be used
193  *
194  * @return Reference voltage in mV
195  * @return 0 on error
196  */
adc_emul_get_ref_voltage(struct adc_emul_data * data,enum adc_reference ref)197 static uint16_t adc_emul_get_ref_voltage(struct adc_emul_data *data,
198 					 enum adc_reference ref)
199 {
200 	uint16_t voltage;
201 
202 	k_mutex_lock(&data->cfg_mtx, K_FOREVER);
203 
204 	switch (ref) {
205 	case ADC_REF_VDD_1:
206 		voltage = data->ref_vdd;
207 		break;
208 	case ADC_REF_VDD_1_2:
209 		voltage = data->ref_vdd / 2;
210 		break;
211 	case ADC_REF_VDD_1_3:
212 		voltage = data->ref_vdd / 3;
213 		break;
214 	case ADC_REF_VDD_1_4:
215 		voltage = data->ref_vdd / 4;
216 		break;
217 	case ADC_REF_INTERNAL:
218 		voltage = data->ref_int;
219 		break;
220 	case ADC_REF_EXTERNAL0:
221 		voltage = data->ref_ext0;
222 		break;
223 	case ADC_REF_EXTERNAL1:
224 		voltage = data->ref_ext1;
225 		break;
226 	default:
227 		voltage = 0;
228 	}
229 
230 	k_mutex_unlock(&data->cfg_mtx);
231 
232 	return voltage;
233 }
234 
adc_emul_channel_setup(const struct device * dev,const struct adc_channel_cfg * channel_cfg)235 static int adc_emul_channel_setup(const struct device *dev,
236 				  const struct adc_channel_cfg *channel_cfg)
237 {
238 	const struct adc_emul_config *config = dev->config;
239 	struct adc_emul_chan_cfg *emul_chan_cfg;
240 	struct adc_emul_data *data = dev->data;
241 
242 	if (channel_cfg->channel_id >= config->num_channels) {
243 		LOG_ERR("unsupported channel id '%d'", channel_cfg->channel_id);
244 		return -ENOTSUP;
245 	}
246 
247 	if (adc_emul_get_ref_voltage(data, channel_cfg->reference) == 0) {
248 		LOG_ERR("unsupported channel reference '%d'",
249 			channel_cfg->reference);
250 		return -ENOTSUP;
251 	}
252 
253 	if (channel_cfg->differential) {
254 		LOG_ERR("unsupported differential mode");
255 		return -ENOTSUP;
256 	}
257 
258 	emul_chan_cfg = &data->chan_cfg[channel_cfg->channel_id];
259 
260 	k_mutex_lock(&data->cfg_mtx, K_FOREVER);
261 
262 	emul_chan_cfg->gain = channel_cfg->gain;
263 	emul_chan_cfg->ref = channel_cfg->reference;
264 
265 	k_mutex_unlock(&data->cfg_mtx);
266 
267 	return 0;
268 }
269 
270 /**
271  * @brief Check if buffer in @p sequence is big enough to hold all ADC samples
272  *
273  * @param dev ADC emulator device
274  * @param sequence ADC sequence description
275  *
276  * @return 0 on success
277  * @return -ENOMEM if buffer is not big enough
278  */
adc_emul_check_buffer_size(const struct device * dev,const struct adc_sequence * sequence)279 static int adc_emul_check_buffer_size(const struct device *dev,
280 					 const struct adc_sequence *sequence)
281 {
282 	const struct adc_emul_config *config = dev->config;
283 	uint8_t channels = 0;
284 	size_t needed;
285 	uint32_t mask;
286 
287 	for (mask = BIT(config->num_channels - 1); mask != 0; mask >>= 1) {
288 		if (mask & sequence->channels) {
289 			channels++;
290 		}
291 	}
292 
293 	needed = channels * sizeof(adc_emul_res_t);
294 	if (sequence->options) {
295 		needed *= (1 + sequence->options->extra_samplings);
296 	}
297 
298 	if (sequence->buffer_size < needed) {
299 		return -ENOMEM;
300 	}
301 
302 	return 0;
303 }
304 
305 /**
306  * @brief Start processing read request
307  *
308  * @param dev ADC emulator device
309  * @param sequence ADC sequence description
310  *
311  * @return 0 on success
312  * @return -ENOTSUP if requested resolution or channel is out side of supported
313  *         range
314  * @return -ENOMEM if buffer is not big enough
315  *         (see @ref adc_emul_check_buffer_size)
316  * @return other error code returned by adc_context_wait_for_completion
317  */
adc_emul_start_read(const struct device * dev,const struct adc_sequence * sequence)318 static int adc_emul_start_read(const struct device *dev,
319 			       const struct adc_sequence *sequence)
320 {
321 	const struct adc_emul_config *config = dev->config;
322 	struct adc_emul_data *data = dev->data;
323 	int err;
324 
325 	if (sequence->resolution > ADC_EMUL_MAX_RESOLUTION ||
326 	    sequence->resolution == 0) {
327 		LOG_ERR("unsupported resolution %d", sequence->resolution);
328 		return -ENOTSUP;
329 	}
330 
331 	if (find_msb_set(sequence->channels) > config->num_channels) {
332 		LOG_ERR("unsupported channels in mask: 0x%08x",
333 			sequence->channels);
334 		return -ENOTSUP;
335 	}
336 
337 	err = adc_emul_check_buffer_size(dev, sequence);
338 	if (err) {
339 		LOG_ERR("buffer size too small");
340 		return err;
341 	}
342 
343 	data->res_mask = BIT_MASK(sequence->resolution);
344 	data->buf = sequence->buffer;
345 	adc_context_start_read(&data->ctx, sequence);
346 
347 	return adc_context_wait_for_completion(&data->ctx);
348 }
349 
adc_emul_read_async(const struct device * dev,const struct adc_sequence * sequence,struct k_poll_signal * async)350 static int adc_emul_read_async(const struct device *dev,
351 			       const struct adc_sequence *sequence,
352 			       struct k_poll_signal *async)
353 {
354 	struct adc_emul_data *data = dev->data;
355 	int err;
356 
357 	adc_context_lock(&data->ctx, async ? true : false, async);
358 	err = adc_emul_start_read(dev, sequence);
359 	adc_context_release(&data->ctx, err);
360 
361 	return err;
362 }
363 
adc_emul_read(const struct device * dev,const struct adc_sequence * sequence)364 static int adc_emul_read(const struct device *dev,
365 			 const struct adc_sequence *sequence)
366 {
367 	return adc_emul_read_async(dev, sequence, NULL);
368 }
369 
adc_context_start_sampling(struct adc_context * ctx)370 static void adc_context_start_sampling(struct adc_context *ctx)
371 {
372 	struct adc_emul_data *data = CONTAINER_OF(ctx, struct adc_emul_data,
373 						  ctx);
374 
375 	data->channels = ctx->sequence.channels;
376 	data->repeat_buf = data->buf;
377 
378 	k_sem_give(&data->sem);
379 }
380 
adc_context_update_buffer_pointer(struct adc_context * ctx,bool repeat_sampling)381 static void adc_context_update_buffer_pointer(struct adc_context *ctx,
382 					      bool repeat_sampling)
383 {
384 	struct adc_emul_data *data = CONTAINER_OF(ctx, struct adc_emul_data,
385 						  ctx);
386 
387 	if (repeat_sampling) {
388 		data->buf = data->repeat_buf;
389 	}
390 }
391 
392 /**
393  * @brief Convert input voltage of ADC @p chan to raw output value
394  *
395  * @param data Internal data of ADC emulator
396  * @param chan ADC channel to sample
397  * @param result Raw output value
398  *
399  * @return 0 on success
400  * @return -EINVAL if failed to get reference voltage or unknown input is
401  *         selected
402  * @return other error code returned by custom function
403  */
adc_emul_get_chan_value(struct adc_emul_data * data,unsigned int chan,adc_emul_res_t * result)404 static int adc_emul_get_chan_value(struct adc_emul_data *data,
405 				   unsigned int chan,
406 				   adc_emul_res_t *result)
407 {
408 	struct adc_emul_chan_cfg *chan_cfg = &data->chan_cfg[chan];
409 	uint32_t input_mV;
410 	uint32_t ref_v;
411 	uint64_t temp; /* Temporary 64 bit value prevent overflows */
412 	int err = 0;
413 
414 	k_mutex_lock(&data->cfg_mtx, K_FOREVER);
415 
416 	/* Get input voltage */
417 	switch (chan_cfg->input) {
418 	case ADC_EMUL_CONST_VALUE:
419 		input_mV = chan_cfg->const_value;
420 		break;
421 
422 	case ADC_EMUL_CUSTOM_FUNC:
423 		err = chan_cfg->func(data->dev, chan, chan_cfg->func_data,
424 				     &input_mV);
425 		if (err) {
426 			LOG_ERR("failed to read channel %d (err %d)",
427 				chan, err);
428 			goto out;
429 		}
430 		break;
431 
432 	default:
433 		LOG_ERR("unknown input source %d", chan_cfg->input);
434 		err = -EINVAL;
435 		goto out;
436 	}
437 
438 	/* Get reference voltage and apply inverted gain */
439 	ref_v = adc_emul_get_ref_voltage(data, chan_cfg->ref);
440 	err = adc_gain_invert(chan_cfg->gain, &ref_v);
441 	if (ref_v == 0 || err) {
442 		LOG_ERR("failed to get ref voltage (channel %d)", chan);
443 		err = -EINVAL;
444 		goto out;
445 	}
446 
447 	/* Calculate output value */
448 	temp = (uint64_t)input_mV * data->res_mask / ref_v;
449 
450 	/* If output value is greater than resolution, it has to be trimmed */
451 	if (temp > data->res_mask) {
452 		temp = data->res_mask;
453 	}
454 
455 	*result = temp;
456 
457 out:
458 	k_mutex_unlock(&data->cfg_mtx);
459 
460 	return err;
461 }
462 
463 /**
464  * @brief Main function of thread which is used to collect samples from
465  *        emulated ADC. When adc_context_start_sampling give semaphore,
466  *        for each requested channel value function is called. Returned
467  *        mV value is converted to output using reference voltage, gain
468  *        and requested resolution.
469  *
470  * @param data Internal data of ADC emulator
471  *
472  * @return This thread should not end
473  */
adc_emul_acquisition_thread(struct adc_emul_data * data)474 static void adc_emul_acquisition_thread(struct adc_emul_data *data)
475 {
476 	int err;
477 
478 	while (true) {
479 		k_sem_take(&data->sem, K_FOREVER);
480 
481 		err = 0;
482 
483 		while (data->channels) {
484 			adc_emul_res_t result = 0;
485 			unsigned int chan = find_lsb_set(data->channels) - 1;
486 
487 			LOG_DBG("reading channel %d", chan);
488 
489 			err = adc_emul_get_chan_value(data, chan, &result);
490 			if (err) {
491 				adc_context_complete(&data->ctx, err);
492 				break;
493 			}
494 
495 			LOG_DBG("read channel %d, result = %d", chan, result);
496 
497 			*data->buf++ = result;
498 			WRITE_BIT(data->channels, chan, 0);
499 		}
500 
501 		if (!err) {
502 			adc_context_on_sampling_done(&data->ctx, data->dev);
503 		}
504 	}
505 }
506 
507 /**
508  * @brief Function called on init for each ADC emulator device. It setups all
509  *        channels to return constant 0 mV and create acquisition thread.
510  *
511  * @param dev ADC emulator device
512  *
513  * @return 0 on success
514  */
adc_emul_init(const struct device * dev)515 static int adc_emul_init(const struct device *dev)
516 {
517 	const struct adc_emul_config *config = dev->config;
518 	struct adc_emul_data *data = dev->data;
519 	int chan;
520 
521 	data->dev = dev;
522 
523 	k_sem_init(&data->sem, 0, 1);
524 	k_mutex_init(&data->cfg_mtx);
525 
526 	for (chan = 0; chan < config->num_channels; chan++) {
527 		struct adc_emul_chan_cfg *chan_cfg = &data->chan_cfg[chan];
528 
529 		chan_cfg->func = NULL;
530 		chan_cfg->func_data = NULL;
531 		chan_cfg->input = ADC_EMUL_CONST_VALUE;
532 		chan_cfg->const_value = 0;
533 	}
534 
535 	k_thread_create(&data->thread, data->stack,
536 			CONFIG_ADC_EMUL_ACQUISITION_THREAD_STACK_SIZE,
537 			(k_thread_entry_t)adc_emul_acquisition_thread,
538 			data, NULL, NULL,
539 			CONFIG_ADC_EMUL_ACQUISITION_THREAD_PRIO,
540 			0, K_NO_WAIT);
541 
542 	adc_context_unlock_unconditionally(&data->ctx);
543 
544 	return 0;
545 }
546 
547 #define ADC_EMUL_INIT(_num)						\
548 	static struct adc_driver_api adc_emul_api_##_num = {		\
549 		.channel_setup = adc_emul_channel_setup,		\
550 		.read = adc_emul_read,					\
551 		.ref_internal = DT_INST_PROP(_num, ref_internal_mv),	\
552 		IF_ENABLED(CONFIG_ADC_ASYNC,				\
553 			(.read_async = adc_emul_read_async,))		\
554 	};								\
555 									\
556 	static struct adc_emul_chan_cfg					\
557 		adc_emul_ch_cfg_##_num[DT_INST_PROP(_num, nchannels)];	\
558 									\
559 	static const struct adc_emul_config adc_emul_config_##_num = {	\
560 		.num_channels = DT_INST_PROP(_num, nchannels),		\
561 	};								\
562 									\
563 	static struct adc_emul_data adc_emul_data_##_num = {		\
564 		ADC_CONTEXT_INIT_TIMER(adc_emul_data_##_num, ctx),	\
565 		ADC_CONTEXT_INIT_LOCK(adc_emul_data_##_num, ctx),	\
566 		ADC_CONTEXT_INIT_SYNC(adc_emul_data_##_num, ctx),	\
567 		.chan_cfg = adc_emul_ch_cfg_##_num,			\
568 		.ref_vdd = DT_INST_PROP(_num, ref_vdd_mv),		\
569 		.ref_ext0 = DT_INST_PROP(_num, ref_external0_mv),	\
570 		.ref_ext1 = DT_INST_PROP(_num, ref_external1_mv),	\
571 		.ref_int = DT_INST_PROP(_num, ref_internal_mv),		\
572 	};								\
573 									\
574 	DEVICE_DT_INST_DEFINE(_num, adc_emul_init, NULL,		\
575 			      &adc_emul_data_##_num,			\
576 			      &adc_emul_config_##_num, POST_KERNEL,	\
577 			      CONFIG_KERNEL_INIT_PRIORITY_DEVICE,	\
578 			      &adc_emul_api_##_num)
579 
580 DT_INST_FOREACH_STATUS_OKAY(ADC_EMUL_INIT);
581