2 * This file is part of the libsigrok project.
4 * Copyright (C) 2013 Marc Schink <sigrok-dev@marcschink.de>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include "libsigrok.h"
24 #include "libsigrok-internal.h"
26 #define LOG_PREFIX "input/csv"
29 * The CSV input module has the following options:
31 * single-column: Specifies the column number which stores the sample data for
32 * single column mode and enables single column mode. Multi
33 * column mode is used if this parameter is omitted.
35 * numprobes: Specifies the number of probes to use. In multi column mode
36 * the number of probes are the number of columns and in single
37 * column mode the number of bits (LSB first) beginning at
40 * delimiter: Specifies the delimiter for columns. Must be at least one
41 * character. Comma is used as default delimiter.
43 * format: Specifies the format of the sample data in single column mode.
44 * Available formats are: 'bin', 'hex' and 'oct'. The binary
45 * format is used by default. This option has no effect in multi
48 * comment: Specifies the prefix character(s) for comments. No prefix
49 * characters are used by default which disables removing of
52 * samplerate: Samplerate which the sample data was captured with. Default
55 * first-probe: Column number of the first probe in multi column mode and
56 * position of the bit for the first probe in single column mode.
59 * header: Determines if the first line should be treated as header
60 * and used for probe names in multi column mode. Empty header
61 * names will be replaced by the probe number. If enabled in
62 * single column mode the first line will be skipped. Usage of
63 * header is disabled by default.
65 * startline: Line number to start processing sample data. Must be greater
66 * than 0. The default line number to start processing is 1.
69 /* Single column formats. */
77 /* Current selected samplerate. */
80 /* Number of probes. */
83 /* Column delimiter character(s). */
86 /* Comment prefix character(s). */
89 /* Determines if sample data is stored in multiple columns. */
90 gboolean multi_column_mode;
92 /* Column number of the sample data in single column mode. */
96 * Number of the first column to parse. Equivalent to the number of the
97 * first probe in multi column mode and the single column number in
103 * Column number of the first probe in multi column mode and position of
104 * the bit for the first probe in single column mode.
108 /* Line number to start processing. */
112 * Determines if the first line should be treated as header and used for
113 * probe names in multi column mode.
117 /* Format sample data is stored in single column mode. */
120 /* Size of the sample buffer. */
121 gsize sample_buffer_size;
123 /* Buffer to store sample data. */
124 uint8_t *sample_buffer;
128 /* Buffer for the current line. */
131 /* Current line number. */
135 static int format_match(const char *filename)
138 sr_err("%s: filename was NULL.", __func__);
142 if (!g_file_test(filename, G_FILE_TEST_EXISTS)) {
143 sr_err("Input file '%s' does not exist.", filename);
147 if (!g_file_test(filename, G_FILE_TEST_IS_REGULAR)) {
148 sr_err("Input file '%s' not a regular file.", filename);
155 static void free_context(struct context *ctx)
161 g_string_free(ctx->delimiter, TRUE);
164 g_string_free(ctx->comment, TRUE);
167 g_io_channel_shutdown(ctx->channel, FALSE, NULL);
168 g_io_channel_unref(ctx->channel);
171 if (ctx->sample_buffer)
172 g_free(ctx->sample_buffer);
175 g_string_free(ctx->buffer, TRUE);
180 static void strip_comment(GString *string, const GString *prefix)
187 if (!(ptr = strstr(string->str, prefix->str)))
190 g_string_truncate(string, ptr - string->str);
193 static int parse_binstr(const char *str, struct context *ctx)
197 length = strlen(str);
200 sr_err("Column %zu in line %zu is empty.", ctx->single_column,
205 /* Clear buffer in order to set bits only. */
206 memset(ctx->sample_buffer, 0, (ctx->num_probes + 7) >> 3);
208 i = ctx->first_probe;
210 for (j = 0; i < length && j < ctx->num_probes; i++, j++) {
211 if (str[length - i - 1] == '1') {
212 ctx->sample_buffer[j / 8] |= (1 << (j % 8));
213 } else if (str[length - i - 1] != '0') {
214 sr_err("Invalid value '%s' in column %zu in line %zu.",
215 str, ctx->single_column, ctx->line_number);
223 static int parse_hexstr(const char *str, struct context *ctx)
225 gsize i, j, k, length;
229 length = strlen(str);
232 sr_err("Column %zu in line %zu is empty.", ctx->single_column,
237 /* Clear buffer in order to set bits only. */
238 memset(ctx->sample_buffer, 0, (ctx->num_probes + 7) >> 3);
240 /* Calculate the position of the first hexadecimal digit. */
241 i = ctx->first_probe / 4;
243 for (j = 0; i < length && j < ctx->num_probes; i++) {
244 c = str[length - i - 1];
246 if (!g_ascii_isxdigit(c)) {
247 sr_err("Invalid value '%s' in column %zu in line %zu.",
248 str, ctx->single_column, ctx->line_number);
252 value = g_ascii_xdigit_value(c);
254 k = (ctx->first_probe + j) % 4;
256 for (; j < ctx->num_probes && k < 4; k++) {
257 if (value & (1 << k))
258 ctx->sample_buffer[j / 8] |= (1 << (j % 8));
267 static int parse_octstr(const char *str, struct context *ctx)
269 gsize i, j, k, length;
273 length = strlen(str);
276 sr_err("Column %zu in line %zu is empty.", ctx->single_column,
281 /* Clear buffer in order to set bits only. */
282 memset(ctx->sample_buffer, 0, (ctx->num_probes + 7) >> 3);
284 /* Calculate the position of the first octal digit. */
285 i = ctx->first_probe / 3;
287 for (j = 0; i < length && j < ctx->num_probes; i++) {
288 c = str[length - i - 1];
290 if (c < '0' || c > '7') {
291 sr_err("Invalid value '%s' in column %zu in line %zu.",
292 str, ctx->single_column, ctx->line_number);
296 value = g_ascii_xdigit_value(c);
298 k = (ctx->first_probe + j) % 3;
300 for (; j < ctx->num_probes && k < 3; k++) {
301 if (value & (1 << k))
302 ctx->sample_buffer[j / 8] |= (1 << (j % 8));
311 static char **parse_line(const struct context *ctx, int max_columns)
313 const char *str, *remainder;
323 remainder = ctx->buffer->str;
324 str = strstr(remainder, ctx->delimiter->str);
326 while (str && max_columns) {
327 if (n >= ctx->first_column) {
328 column = g_strndup(remainder, str - remainder);
329 list = g_slist_prepend(list, g_strstrip(column));
335 remainder = str + ctx->delimiter->len;
336 str = strstr(remainder, ctx->delimiter->str);
340 if (ctx->buffer->len && max_columns && n >= ctx->first_column) {
341 column = g_strdup(remainder);
342 list = g_slist_prepend(list, g_strstrip(column));
346 if (!(columns = g_try_new(char *, k + 1)))
351 for (l = list; l; l = l->next)
352 columns[k--] = l->data;
359 static int parse_multi_columns(char **columns, struct context *ctx)
363 /* Clear buffer in order to set bits only. */
364 memset(ctx->sample_buffer, 0, (ctx->num_probes + 7) >> 3);
366 for (i = 0; i < ctx->num_probes; i++) {
367 if (columns[i][0] == '1') {
368 ctx->sample_buffer[i / 8] |= (1 << (i % 8));
369 } else if (!strlen(columns[i])) {
370 sr_err("Column %zu in line %zu is empty.",
371 ctx->first_probe + i, ctx->line_number);
373 } else if (columns[i][0] != '0') {
374 sr_err("Invalid value '%s' in column %zu in line %zu.",
375 columns[i], ctx->first_probe + i,
384 static int parse_single_column(const char *column, struct context *ctx)
390 switch(ctx->format) {
392 res = parse_binstr(column, ctx);
395 res = parse_hexstr(column, ctx);
398 res = parse_octstr(column, ctx);
405 static int send_samples(const struct sr_dev_inst *sdi, uint8_t *buffer,
406 gsize buffer_size, gsize count)
409 struct sr_datafeed_packet packet;
410 struct sr_datafeed_logic logic;
413 packet.type = SR_DF_LOGIC;
414 packet.payload = &logic;
415 logic.unitsize = buffer_size;
416 logic.length = buffer_size;
419 for (i = 0; i < count; i++) {
420 if ((res = sr_session_send(sdi, &packet)) != SR_OK)
427 static int init(struct sr_input *in, const char *filename)
434 char probe_name[SR_MAX_PROBENAME_LEN + 1];
435 struct sr_probe *probe;
440 if (!(ctx = g_try_malloc0(sizeof(struct context)))) {
441 sr_err("Context malloc failed.");
442 return SR_ERR_MALLOC;
445 /* Create a virtual device. */
446 in->sdi = sr_dev_inst_new(0, SR_ST_ACTIVE, NULL, NULL, NULL);
449 /* Set default samplerate. */
453 * Enable auto-detection of the number of probes in multi column mode
454 * and enforce the specification of the number of probes in single
459 /* Set default delimiter. */
460 if (!(ctx->delimiter = g_string_new(","))) {
461 sr_err("Delimiter malloc failed.");
463 return SR_ERR_MALLOC;
467 * Set default comment prefix. Note that an empty comment prefix
468 * disables removing of comments.
470 if (!(ctx->comment = g_string_new(""))) {
471 sr_err("Comment malloc failed.");
473 return SR_ERR_MALLOC;
476 /* Enable multi column mode by default. */
477 ctx->multi_column_mode = TRUE;
479 /* Use first column as default single column number. */
480 ctx->single_column = 0;
483 * In multi column mode start parsing sample data at the first column
484 * and in single column mode at the first bit.
486 ctx->first_probe = 0;
488 /* Start at the beginning of the file. */
491 /* Disable the usage of the first line as header by default. */
494 /* Set default format for single column mode. */
495 ctx->format = FORMAT_BIN;
497 if (!(ctx->buffer = g_string_new(""))) {
498 sr_err("Line buffer malloc failed.");
500 return SR_ERR_MALLOC;
504 if ((param = g_hash_table_lookup(in->param, "samplerate"))) {
505 res = sr_parse_sizestring(param, &ctx->samplerate);
508 sr_err("Invalid samplerate: %s.", param);
514 if ((param = g_hash_table_lookup(in->param, "numprobes")))
515 ctx->num_probes = g_ascii_strtoull(param, NULL, 10);
517 if ((param = g_hash_table_lookup(in->param, "delimiter"))) {
518 if (!strlen(param)) {
519 sr_err("Delimiter must be at least one character.");
524 if (!g_ascii_strcasecmp(param, "\\t"))
525 g_string_assign(ctx->delimiter, "\t");
527 g_string_assign(ctx->delimiter, param);
530 if ((param = g_hash_table_lookup(in->param, "comment")))
531 g_string_assign(ctx->comment, param);
533 if ((param = g_hash_table_lookup(in->param, "single-column"))) {
534 ctx->single_column = g_ascii_strtoull(param, &ptr, 10);
535 ctx->multi_column_mode = FALSE;
538 sr_err("Invalid single-colum number: %s.",
545 if ((param = g_hash_table_lookup(in->param, "first-probe")))
546 ctx->first_probe = g_ascii_strtoull(param, NULL, 10);
548 if ((param = g_hash_table_lookup(in->param, "startline"))) {
549 ctx->start_line = g_ascii_strtoull(param, NULL, 10);
551 if (ctx->start_line < 1) {
552 sr_err("Invalid start line: %s.", param);
558 if ((param = g_hash_table_lookup(in->param, "header")))
559 ctx->header = sr_parse_boolstring(param);
561 if ((param = g_hash_table_lookup(in->param, "format"))) {
562 if (!g_ascii_strncasecmp(param, "bin", 3)) {
563 ctx->format = FORMAT_BIN;
564 } else if (!g_ascii_strncasecmp(param, "hex", 3)) {
565 ctx->format = FORMAT_HEX;
566 } else if (!g_ascii_strncasecmp(param, "oct", 3)) {
567 ctx->format = FORMAT_OCT;
569 sr_err("Invalid format: %s.", param);
576 if (ctx->multi_column_mode)
577 ctx->first_column = ctx->first_probe;
579 ctx->first_column = ctx->single_column;
581 if (!ctx->multi_column_mode && !ctx->num_probes) {
582 sr_err("Number of probes needs to be specified in single column mode.");
587 if (!(ctx->channel = g_io_channel_new_file(filename, "r", NULL))) {
588 sr_err("Input file '%s' could not be opened.", filename);
595 status = g_io_channel_read_line_string(ctx->channel,
596 ctx->buffer, &term_pos, NULL);
598 if (status == G_IO_STATUS_EOF) {
599 sr_err("Input file is empty.");
604 if (status != G_IO_STATUS_NORMAL) {
605 sr_err("Error while reading line %zu.",
611 if (ctx->start_line > ctx->line_number) {
612 sr_spew("Line %zu skipped.", ctx->line_number);
616 /* Remove line termination character(s). */
617 g_string_truncate(ctx->buffer, term_pos);
619 if (!ctx->buffer->len) {
620 sr_spew("Blank line %zu skipped.", ctx->line_number);
624 /* Remove trailing comment. */
625 strip_comment(ctx->buffer, ctx->comment);
627 if (ctx->buffer->len)
630 sr_spew("Comment-only line %zu skipped.", ctx->line_number);
634 * In order to determine the number of columns parse the current line
635 * without limiting the number of columns.
637 if (!(columns = parse_line(ctx, -1))) {
638 sr_err("Error while parsing line %zu.", ctx->line_number);
643 num_columns = g_strv_length(columns);
645 /* Ensure that the first column is not out of bounds. */
647 sr_err("Column %zu in line %zu is out of bounds.",
648 ctx->first_column, ctx->line_number);
654 if (ctx->multi_column_mode) {
656 * Detect the number of probes in multi column mode
657 * automatically if not specified.
659 if (!ctx->num_probes) {
660 ctx->num_probes = num_columns;
661 sr_info("Number of auto-detected probes: %zu.",
666 * Ensure that the number of probes does not exceed the number
667 * of columns in multi column mode.
669 if (num_columns < ctx->num_probes) {
670 sr_err("Not enough columns for desired number of probes in line %zu.",
678 for (i = 0; i < ctx->num_probes; i++) {
679 if (ctx->header && ctx->multi_column_mode && strlen(columns[i]))
680 snprintf(probe_name, sizeof(probe_name), "%s",
683 snprintf(probe_name, sizeof(probe_name), "%zu", i);
685 probe = sr_probe_new(i, SR_PROBE_LOGIC, TRUE, probe_name);
688 sr_err("Probe creation failed.");
694 in->sdi->probes = g_slist_append(in->sdi->probes, probe);
700 * Calculate the minimum buffer size to store the sample data of the
703 ctx->sample_buffer_size = (ctx->num_probes + 7) >> 3;
705 if (!(ctx->sample_buffer = g_try_malloc(ctx->sample_buffer_size))) {
706 sr_err("Sample buffer malloc failed.");
708 return SR_ERR_MALLOC;
714 static int loadfile(struct sr_input *in, const char *filename)
718 struct sr_datafeed_packet packet;
719 struct sr_datafeed_meta meta;
720 struct sr_config *cfg;
722 gboolean read_new_line;
732 /* Send header packet to the session bus. */
733 std_session_send_df_header(in->sdi, LOG_PREFIX);
735 if (ctx->samplerate) {
736 packet.type = SR_DF_META;
737 packet.payload = &meta;
738 cfg = sr_config_new(SR_CONF_SAMPLERATE,
739 g_variant_new_uint64(ctx->samplerate));
740 meta.config = g_slist_append(NULL, cfg);
741 sr_session_send(in->sdi, &packet);
745 read_new_line = FALSE;
747 /* Limit the number of columns to parse. */
748 if (ctx->multi_column_mode)
749 max_columns = ctx->num_probes;
755 * Skip reading a new line for the first time if the last read
756 * line was not a header because the sample data is not parsed
759 if (read_new_line || ctx->header) {
761 status = g_io_channel_read_line_string(ctx->channel,
762 ctx->buffer, &term_pos, NULL);
764 if (status == G_IO_STATUS_EOF)
767 if (status != G_IO_STATUS_NORMAL) {
768 sr_err("Error while reading line %zu.",
774 /* Remove line termination character(s). */
775 g_string_truncate(ctx->buffer, term_pos);
778 read_new_line = TRUE;
780 if (!ctx->buffer->len) {
781 sr_spew("Blank line %zu skipped.", ctx->line_number);
785 /* Remove trailing comment. */
786 strip_comment(ctx->buffer, ctx->comment);
788 if (!ctx->buffer->len) {
789 sr_spew("Comment-only line %zu skipped.",
794 if (!(columns = parse_line(ctx, max_columns))) {
795 sr_err("Error while parsing line %zu.",
801 num_columns = g_strv_length(columns);
803 /* Ensure that the first column is not out of bounds. */
805 sr_err("Column %zu in line %zu is out of bounds.",
806 ctx->first_column, ctx->line_number);
813 * Ensure that the number of probes does not exceed the number
814 * of columns in multi column mode.
816 if (ctx->multi_column_mode && num_columns < ctx->num_probes) {
817 sr_err("Not enough columns for desired number of probes in line %zu.",
824 if (ctx->multi_column_mode)
825 res = parse_multi_columns(columns, ctx);
827 res = parse_single_column(columns[0], ctx);
838 * TODO: Parse sample numbers / timestamps and use it for
842 /* Send sample data to the session bus. */
843 res = send_samples(in->sdi, ctx->sample_buffer,
844 ctx->sample_buffer_size, 1);
847 sr_err("Sending samples failed.");
853 /* Send end packet to the session bus. */
854 packet.type = SR_DF_END;
855 sr_session_send(in->sdi, &packet);
862 SR_PRIV struct sr_input_format input_csv = {
864 .description = "Comma-separated values (CSV)",
865 .format_match = format_match,
867 .loadfile = loadfile,