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 /* Message logging helpers with subsystem-specific prefix string. */
27 #define LOG_PREFIX "input/csv: "
28 #define sr_log(l, s, args...) sr_log(l, LOG_PREFIX s, ## args)
29 #define sr_spew(s, args...) sr_spew(LOG_PREFIX s, ## args)
30 #define sr_dbg(s, args...) sr_dbg(LOG_PREFIX s, ## args)
31 #define sr_info(s, args...) sr_info(LOG_PREFIX s, ## args)
32 #define sr_warn(s, args...) sr_warn(LOG_PREFIX s, ## args)
33 #define sr_err(s, args...) sr_err(LOG_PREFIX s, ## args)
36 * The CSV input module has the following options:
38 * single-column: Specifies the column number which stores the sample data for
39 * single column mode and enables single column mode. Multi
40 * column mode is used if this parameter is omitted.
42 * numprobes: Specifies the number of probes to use. In multi column mode
43 * the number of probes are the number of columns and in single
44 * column mode the number of bits (LSB first) beginning at
47 * delimiter: Specifies the delimiter for columns. Must be at least one
48 * character. Comma is used as default delimiter.
50 * format: Specifies the format of the sample data in single column mode.
51 * Available formats are: 'bin', 'hex' and 'oct'. The binary
52 * format is used by default. This option has no effect in multi
55 * comment: Specifies the prefix character(s) for comments. No prefix
56 * characters are used by default which disables removing of
59 * samplerate: Samplerate which the sample data was captured with. Default
62 * first-probe: Column number of the first probe in multi column mode and
63 * position of the bit for the first probe in single column mode.
66 * header: Determines if the first line should be treated as header
67 * and used for probe names in multi column mode. Empty header
68 * names will be replaced by the probe number. If enabled in
69 * single column mode the first line will be skipped. Usage of
70 * header is disabled by default.
72 * startline: Line number to start processing sample data. Must be greater
73 * than 0. The default line number to start processing is 1.
76 /* Single column formats. */
84 /* Current selected samplerate. */
87 /* Number of probes. */
90 /* Column delimiter character(s). */
93 /* Comment prefix character(s). */
96 /* Determines if sample data is stored in multiple columns. */
97 gboolean multi_column_mode;
99 /* Column number of the sample data in single column mode. */
103 * Number of the first column to parse. Equivalent to the number of the
104 * first probe in multi column mode and the single column number in
105 * single column mode.
110 * Column number of the first probe in multi column mode and position of
111 * the bit for the first probe in single column mode.
115 /* Line number to start processing. */
119 * Determines if the first line should be treated as header and used for
120 * probe names in multi column mode.
124 /* Format sample data is stored in single column mode. */
127 /* Size of the sample buffer. */
128 gsize sample_buffer_size;
130 /* Buffer to store sample data. */
131 uint8_t *sample_buffer;
135 /* Buffer for the current line. */
138 /* Current line number. */
142 static int format_match(const char *filename)
145 sr_err("%s: filename was NULL.", __func__);
149 if (!g_file_test(filename, G_FILE_TEST_EXISTS)) {
150 sr_err("Input file '%s' does not exist.", filename);
154 if (!g_file_test(filename, G_FILE_TEST_IS_REGULAR)) {
155 sr_err("Input file '%s' not a regular file.", filename);
162 static void free_context(struct context *ctx)
168 g_string_free(ctx->delimiter, TRUE);
171 g_string_free(ctx->comment, TRUE);
174 g_io_channel_shutdown(ctx->channel, FALSE, NULL);
175 g_io_channel_unref(ctx->channel);
178 if (ctx->sample_buffer)
179 g_free(ctx->sample_buffer);
182 g_string_free(ctx->buffer, TRUE);
187 static void strip_comment(GString *string, const GString *prefix)
194 if (!(ptr = strstr(string->str, prefix->str)))
197 g_string_truncate(string, ptr - string->str);
200 static int parse_binstr(const char *str, struct context *ctx)
204 length = strlen(str);
207 sr_err("Column %zu in line %zu is empty.", ctx->single_column,
212 /* Clear buffer in order to set bits only. */
213 memset(ctx->sample_buffer, 0, (ctx->num_probes + 7) >> 3);
215 i = ctx->first_probe;
217 for (j = 0; i < length && j < ctx->num_probes; i++, j++) {
218 if (str[length - i - 1] == '1') {
219 ctx->sample_buffer[j / 8] |= (1 << (j % 8));
220 } else if (str[length - i - 1] != '0') {
221 sr_err("Invalid value '%s' in column %zu in line %zu.",
222 str, ctx->single_column, ctx->line_number);
230 static int parse_hexstr(const char *str, struct context *ctx)
232 gsize i, j, k, length;
236 length = strlen(str);
239 sr_err("Column %zu in line %zu is empty.", ctx->single_column,
244 /* Clear buffer in order to set bits only. */
245 memset(ctx->sample_buffer, 0, (ctx->num_probes + 7) >> 3);
247 /* Calculate the position of the first hexadecimal digit. */
248 i = ctx->first_probe / 4;
250 for (j = 0; i < length && j < ctx->num_probes; i++) {
251 c = str[length - i - 1];
253 if (!g_ascii_isxdigit(c)) {
254 sr_err("Invalid value '%s' in column %zu in line %zu.",
255 str, ctx->single_column, ctx->line_number);
259 value = g_ascii_xdigit_value(c);
261 k = (ctx->first_probe + j) % 4;
263 for (; j < ctx->num_probes && k < 4; k++) {
264 if (value & (1 << k))
265 ctx->sample_buffer[j / 8] |= (1 << (j % 8));
274 static int parse_octstr(const char *str, struct context *ctx)
276 gsize i, j, k, length;
280 length = strlen(str);
283 sr_err("Column %zu in line %zu is empty.", ctx->single_column,
288 /* Clear buffer in order to set bits only. */
289 memset(ctx->sample_buffer, 0, (ctx->num_probes + 7) >> 3);
291 /* Calculate the position of the first octal digit. */
292 i = ctx->first_probe / 3;
294 for (j = 0; i < length && j < ctx->num_probes; i++) {
295 c = str[length - i - 1];
297 if (c < '0' || c > '7') {
298 sr_err("Invalid value '%s' in column %zu in line %zu.",
299 str, ctx->single_column, ctx->line_number);
303 value = g_ascii_xdigit_value(c);
305 k = (ctx->first_probe + j) % 3;
307 for (; j < ctx->num_probes && k < 3; k++) {
308 if (value & (1 << k))
309 ctx->sample_buffer[j / 8] |= (1 << (j % 8));
318 static char **parse_line(const struct context *ctx, int max_columns)
320 const char *str, *remainder;
330 remainder = ctx->buffer->str;
331 str = strstr(remainder, ctx->delimiter->str);
333 while (str && max_columns) {
334 if (n >= ctx->first_column) {
335 column = g_strndup(remainder, str - remainder);
336 list = g_slist_prepend(list, g_strstrip(column));
342 remainder = str + ctx->delimiter->len;
343 str = strstr(remainder, ctx->delimiter->str);
347 if (ctx->buffer->len && max_columns && n >= ctx->first_column) {
348 column = g_strdup(remainder);
349 list = g_slist_prepend(list, g_strstrip(column));
353 if (!(columns = g_try_new(char *, k + 1)))
358 for (l = list; l; l = l->next)
359 columns[k--] = l->data;
366 static int parse_multi_columns(char **columns, struct context *ctx)
370 /* Clear buffer in order to set bits only. */
371 memset(ctx->sample_buffer, 0, (ctx->num_probes + 7) >> 3);
373 for (i = 0; i < ctx->num_probes; i++) {
374 if (columns[i][0] == '1') {
375 ctx->sample_buffer[i / 8] |= (1 << (i % 8));
376 } else if (!strlen(columns[i])) {
377 sr_err("Column %zu in line %zu is empty.",
378 ctx->first_probe + i, ctx->line_number);
380 } else if (columns[i][0] != '0') {
381 sr_err("Invalid value '%s' in column %zu in line %zu.",
382 columns[i], ctx->first_probe + i,
391 static int parse_single_column(const char *column, struct context *ctx)
397 switch(ctx->format) {
399 res = parse_binstr(column, ctx);
402 res = parse_hexstr(column, ctx);
405 res = parse_octstr(column, ctx);
412 static int send_samples(const struct sr_dev_inst *sdi, uint8_t *buffer,
413 gsize buffer_size, gsize count)
416 struct sr_datafeed_packet packet;
417 struct sr_datafeed_logic logic;
420 packet.type = SR_DF_LOGIC;
421 packet.payload = &logic;
422 logic.unitsize = buffer_size;
423 logic.length = buffer_size;
426 for (i = 0; i < count; i++) {
427 if ((res = sr_session_send(sdi, &packet)) != SR_OK)
434 static int init(struct sr_input *in, const char *filename)
441 char probe_name[SR_MAX_PROBENAME_LEN + 1];
442 struct sr_probe *probe;
447 if (!(ctx = g_try_malloc0(sizeof(struct context)))) {
448 sr_err("Context malloc failed.");
449 return SR_ERR_MALLOC;
452 /* Create a virtual device. */
453 in->sdi = sr_dev_inst_new(0, SR_ST_ACTIVE, NULL, NULL, NULL);
456 /* Set default samplerate. */
460 * Enable auto-detection of the number of probes in multi column mode
461 * and enforce the specification of the number of probes in single
466 /* Set default delimiter. */
467 if (!(ctx->delimiter = g_string_new(","))) {
468 sr_err("Delimiter malloc failed.");
470 return SR_ERR_MALLOC;
474 * Set default comment prefix. Note that an empty comment prefix
475 * disables removing of comments.
477 if (!(ctx->comment = g_string_new(""))) {
478 sr_err("Comment malloc failed.");
480 return SR_ERR_MALLOC;
483 /* Enable multi column mode by default. */
484 ctx->multi_column_mode = TRUE;
486 /* Use first column as default single column number. */
487 ctx->single_column = 0;
490 * In multi column mode start parsing sample data at the first column
491 * and in single column mode at the first bit.
493 ctx->first_probe = 0;
495 /* Start at the beginning of the file. */
498 /* Disable the usage of the first line as header by default. */
501 /* Set default format for single column mode. */
502 ctx->format = FORMAT_BIN;
504 if (!(ctx->buffer = g_string_new(""))) {
505 sr_err("Line buffer malloc failed.");
507 return SR_ERR_MALLOC;
511 if ((param = g_hash_table_lookup(in->param, "samplerate"))) {
512 res = sr_parse_sizestring(param, &ctx->samplerate);
515 sr_err("Invalid samplerate: %s.", param);
521 if ((param = g_hash_table_lookup(in->param, "numprobes")))
522 ctx->num_probes = g_ascii_strtoull(param, NULL, 10);
524 if ((param = g_hash_table_lookup(in->param, "delimiter"))) {
525 if (!strlen(param)) {
526 sr_err("Delimiter must be at least one character.");
531 if (!g_ascii_strcasecmp(param, "\\t"))
532 g_string_assign(ctx->delimiter, "\t");
534 g_string_assign(ctx->delimiter, param);
537 if ((param = g_hash_table_lookup(in->param, "comment")))
538 g_string_assign(ctx->comment, param);
540 if ((param = g_hash_table_lookup(in->param, "single-column"))) {
541 ctx->single_column = g_ascii_strtoull(param, &ptr, 10);
542 ctx->multi_column_mode = FALSE;
545 sr_err("Invalid single-colum number: %s.",
552 if ((param = g_hash_table_lookup(in->param, "first-probe")))
553 ctx->first_probe = g_ascii_strtoull(param, NULL, 10);
555 if ((param = g_hash_table_lookup(in->param, "startline"))) {
556 ctx->start_line = g_ascii_strtoull(param, NULL, 10);
558 if (ctx->start_line < 1) {
559 sr_err("Invalid start line: %s.", param);
565 if ((param = g_hash_table_lookup(in->param, "header")))
566 ctx->header = sr_parse_boolstring(param);
568 if ((param = g_hash_table_lookup(in->param, "format"))) {
569 if (!g_ascii_strncasecmp(param, "bin", 3)) {
570 ctx->format = FORMAT_BIN;
571 } else if (!g_ascii_strncasecmp(param, "hex", 3)) {
572 ctx->format = FORMAT_HEX;
573 } else if (!g_ascii_strncasecmp(param, "oct", 3)) {
574 ctx->format = FORMAT_OCT;
576 sr_err("Invalid format: %s.", param);
583 if (ctx->multi_column_mode)
584 ctx->first_column = ctx->first_probe;
586 ctx->first_column = ctx->single_column;
588 if (!ctx->multi_column_mode && !ctx->num_probes) {
589 sr_err("Number of probes needs to be specified in single column mode.");
594 if (!(ctx->channel = g_io_channel_new_file(filename, "r", NULL))) {
595 sr_err("Input file '%s' could not be opened.", filename);
602 status = g_io_channel_read_line_string(ctx->channel,
603 ctx->buffer, &term_pos, NULL);
605 if (status == G_IO_STATUS_EOF) {
606 sr_err("Input file is empty.");
611 if (status != G_IO_STATUS_NORMAL) {
612 sr_err("Error while reading line %zu.",
618 if (ctx->start_line > ctx->line_number) {
619 sr_spew("Line %zu skipped.", ctx->line_number);
623 /* Remove line termination character(s). */
624 g_string_truncate(ctx->buffer, term_pos);
626 if (!ctx->buffer->len) {
627 sr_spew("Blank line %zu skipped.", ctx->line_number);
631 /* Remove trailing comment. */
632 strip_comment(ctx->buffer, ctx->comment);
634 if (ctx->buffer->len)
637 sr_spew("Comment-only line %zu skipped.", ctx->line_number);
641 * In order to determine the number of columns parse the current line
642 * without limiting the number of columns.
644 if (!(columns = parse_line(ctx, -1))) {
645 sr_err("Error while parsing line %zu.", ctx->line_number);
650 num_columns = g_strv_length(columns);
652 /* Ensure that the first column is not out of bounds. */
654 sr_err("Column %zu in line %zu is out of bounds.",
655 ctx->first_column, ctx->line_number);
661 if (ctx->multi_column_mode) {
663 * Detect the number of probes in multi column mode
664 * automatically if not specified.
666 if (!ctx->num_probes) {
667 ctx->num_probes = num_columns;
668 sr_info("Number of auto-detected probes: %zu.",
673 * Ensure that the number of probes does not exceed the number
674 * of columns in multi column mode.
676 if (num_columns < ctx->num_probes) {
677 sr_err("Not enough columns for desired number of probes in line %zu.",
685 for (i = 0; i < ctx->num_probes; i++) {
686 if (ctx->header && ctx->multi_column_mode && strlen(columns[i]))
687 snprintf(probe_name, sizeof(probe_name), "%s",
690 snprintf(probe_name, sizeof(probe_name), "%zu", i);
692 probe = sr_probe_new(i, SR_PROBE_LOGIC, TRUE, probe_name);
695 sr_err("Probe creation failed.");
701 in->sdi->probes = g_slist_append(in->sdi->probes, probe);
707 * Calculate the minimum buffer size to store the sample data of the
710 ctx->sample_buffer_size = (ctx->num_probes + 7) >> 3;
712 if (!(ctx->sample_buffer = g_try_malloc(ctx->sample_buffer_size))) {
713 sr_err("Sample buffer malloc failed.");
715 return SR_ERR_MALLOC;
721 static int loadfile(struct sr_input *in, const char *filename)
725 struct sr_datafeed_packet packet;
726 struct sr_datafeed_meta meta;
727 struct sr_config *cfg;
729 gboolean read_new_line;
739 /* Send header packet to the session bus. */
740 std_session_send_df_header(in->sdi, LOG_PREFIX);
742 if (ctx->samplerate) {
743 packet.type = SR_DF_META;
744 packet.payload = &meta;
745 cfg = sr_config_new(SR_CONF_SAMPLERATE,
746 g_variant_new_uint64(ctx->samplerate));
747 meta.config = g_slist_append(NULL, cfg);
748 sr_session_send(in->sdi, &packet);
752 read_new_line = FALSE;
754 /* Limit the number of columns to parse. */
755 if (ctx->multi_column_mode)
756 max_columns = ctx->num_probes;
762 * Skip reading a new line for the first time if the last read
763 * line was not a header because the sample data is not parsed
766 if (read_new_line || ctx->header) {
768 status = g_io_channel_read_line_string(ctx->channel,
769 ctx->buffer, &term_pos, NULL);
771 if (status == G_IO_STATUS_EOF)
774 if (status != G_IO_STATUS_NORMAL) {
775 sr_err("Error while reading line %zu.",
781 /* Remove line termination character(s). */
782 g_string_truncate(ctx->buffer, term_pos);
785 read_new_line = TRUE;
787 if (!ctx->buffer->len) {
788 sr_spew("Blank line %zu skipped.", ctx->line_number);
792 /* Remove trailing comment. */
793 strip_comment(ctx->buffer, ctx->comment);
795 if (!ctx->buffer->len) {
796 sr_spew("Comment-only line %zu skipped.",
801 if (!(columns = parse_line(ctx, max_columns))) {
802 sr_err("Error while parsing line %zu.",
808 num_columns = g_strv_length(columns);
810 /* Ensure that the first column is not out of bounds. */
812 sr_err("Column %zu in line %zu is out of bounds.",
813 ctx->first_column, ctx->line_number);
820 * Ensure that the number of probes does not exceed the number
821 * of columns in multi column mode.
823 if (ctx->multi_column_mode && num_columns < ctx->num_probes) {
824 sr_err("Not enough columns for desired number of probes in line %zu.",
831 if (ctx->multi_column_mode)
832 res = parse_multi_columns(columns, ctx);
834 res = parse_single_column(columns[0], ctx);
845 * TODO: Parse sample numbers / timestamps and use it for
849 /* Send sample data to the session bus. */
850 res = send_samples(in->sdi, ctx->sample_buffer,
851 ctx->sample_buffer_size, 1);
854 sr_err("Sending samples failed.");
860 /* Send end packet to the session bus. */
861 packet.type = SR_DF_END;
862 sr_session_send(in->sdi, &packet);
869 SR_PRIV struct sr_input_format input_csv = {
871 .description = "Comma-separated values (CSV)",
872 .format_match = format_match,
874 .loadfile = loadfile,