1 /*
2  * Copyright (c) 2018 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/shell/shell_fprintf.h>
8 #include <zephyr/shell/shell.h>
9 #include <zephyr/sys/cbprintf.h>
10 
out_func(int c,void * ctx)11 static int out_func(int c, void *ctx)
12 {
13 	const struct shell_fprintf *sh_fprintf;
14 	const struct shell *sh;
15 
16 	sh_fprintf = (const struct shell_fprintf *)ctx;
17 	sh = (const struct shell *)sh_fprintf->user_ctx;
18 
19 	if ((sh->shell_flag == SHELL_FLAG_OLF_CRLF) && (c == '\n')) {
20 		(void)out_func('\r', ctx);
21 	}
22 
23 	sh_fprintf->buffer[sh_fprintf->ctrl_blk->buffer_cnt] = (uint8_t)c;
24 	sh_fprintf->ctrl_blk->buffer_cnt++;
25 
26 	if (sh_fprintf->ctrl_blk->buffer_cnt == sh_fprintf->buffer_size) {
27 		z_shell_fprintf_buffer_flush(sh_fprintf);
28 	}
29 
30 	return 0;
31 }
32 
z_shell_fprintf_fmt(const struct shell_fprintf * sh_fprintf,const char * fmt,va_list args)33 void z_shell_fprintf_fmt(const struct shell_fprintf *sh_fprintf,
34 			 const char *fmt, va_list args)
35 {
36 	(void)cbvprintf(out_func, (void *)sh_fprintf, fmt, args);
37 
38 	if (sh_fprintf->ctrl_blk->autoflush) {
39 		z_shell_fprintf_buffer_flush(sh_fprintf);
40 	}
41 }
42 
43 
z_shell_fprintf_buffer_flush(const struct shell_fprintf * sh_fprintf)44 void z_shell_fprintf_buffer_flush(const struct shell_fprintf *sh_fprintf)
45 {
46 	sh_fprintf->fwrite(sh_fprintf->user_ctx, sh_fprintf->buffer,
47 			   sh_fprintf->ctrl_blk->buffer_cnt);
48 	sh_fprintf->ctrl_blk->buffer_cnt = 0;
49 }
50