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 * numchannels: Specifies the number of channels to use. In multi column mode
36 * the number of channels 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-channel: Column number of the first channel in multi column mode and
56 * position of the bit for the first channel in single column mode.
59 * header: Determines if the first line should be treated as header
60 * and used for channel names in multi column mode. Empty header
61 * names will be replaced by the channel 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 channels. */
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 channel in multi column mode and the single column number in
103 * Column number of the first channel in multi column mode and position of
104 * the bit for the first channel 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 * channel 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)
137 /* Require .csv extension. */
138 if (strcmp(filename + strlen(filename) - 4, ".csv"))
142 sr_err("%s: filename was NULL.", __func__);
146 if (!g_file_test(filename, G_FILE_TEST_EXISTS)) {
147 sr_err("Input file '%s' does not exist.", filename);
151 if (!g_file_test(filename, G_FILE_TEST_IS_REGULAR)) {
152 sr_err("Input file '%s' not a regular file.", filename);
159 static void free_context(struct context *ctx)
165 g_string_free(ctx->delimiter, TRUE);
168 g_string_free(ctx->comment, TRUE);
171 g_io_channel_shutdown(ctx->channel, FALSE, NULL);
172 g_io_channel_unref(ctx->channel);
175 if (ctx->sample_buffer)
176 g_free(ctx->sample_buffer);
179 g_string_free(ctx->buffer, TRUE);
184 static void strip_comment(GString *string, const GString *prefix)
191 if (!(ptr = strstr(string->str, prefix->str)))
194 g_string_truncate(string, ptr - string->str);
197 static int parse_binstr(const char *str, struct context *ctx)
201 length = strlen(str);
204 sr_err("Column %zu in line %zu is empty.", ctx->single_column,
209 /* Clear buffer in order to set bits only. */
210 memset(ctx->sample_buffer, 0, (ctx->num_channels + 7) >> 3);
212 i = ctx->first_channel;
214 for (j = 0; i < length && j < ctx->num_channels; i++, j++) {
215 if (str[length - i - 1] == '1') {
216 ctx->sample_buffer[j / 8] |= (1 << (j % 8));
217 } else if (str[length - i - 1] != '0') {
218 sr_err("Invalid value '%s' in column %zu in line %zu.",
219 str, ctx->single_column, ctx->line_number);
227 static int parse_hexstr(const char *str, struct context *ctx)
229 gsize i, j, k, length;
233 length = strlen(str);
236 sr_err("Column %zu in line %zu is empty.", ctx->single_column,
241 /* Clear buffer in order to set bits only. */
242 memset(ctx->sample_buffer, 0, (ctx->num_channels + 7) >> 3);
244 /* Calculate the position of the first hexadecimal digit. */
245 i = ctx->first_channel / 4;
247 for (j = 0; i < length && j < ctx->num_channels; i++) {
248 c = str[length - i - 1];
250 if (!g_ascii_isxdigit(c)) {
251 sr_err("Invalid value '%s' in column %zu in line %zu.",
252 str, ctx->single_column, ctx->line_number);
256 value = g_ascii_xdigit_value(c);
258 k = (ctx->first_channel + j) % 4;
260 for (; j < ctx->num_channels && k < 4; k++) {
261 if (value & (1 << k))
262 ctx->sample_buffer[j / 8] |= (1 << (j % 8));
271 static int parse_octstr(const char *str, struct context *ctx)
273 gsize i, j, k, length;
277 length = strlen(str);
280 sr_err("Column %zu in line %zu is empty.", ctx->single_column,
285 /* Clear buffer in order to set bits only. */
286 memset(ctx->sample_buffer, 0, (ctx->num_channels + 7) >> 3);
288 /* Calculate the position of the first octal digit. */
289 i = ctx->first_channel / 3;
291 for (j = 0; i < length && j < ctx->num_channels; i++) {
292 c = str[length - i - 1];
294 if (c < '0' || c > '7') {
295 sr_err("Invalid value '%s' in column %zu in line %zu.",
296 str, ctx->single_column, ctx->line_number);
300 value = g_ascii_xdigit_value(c);
302 k = (ctx->first_channel + j) % 3;
304 for (; j < ctx->num_channels && k < 3; k++) {
305 if (value & (1 << k))
306 ctx->sample_buffer[j / 8] |= (1 << (j % 8));
315 static char **parse_line(const struct context *ctx, int max_columns)
317 const char *str, *remainder;
327 remainder = ctx->buffer->str;
328 str = strstr(remainder, ctx->delimiter->str);
330 while (str && max_columns) {
331 if (n >= ctx->first_column) {
332 column = g_strndup(remainder, str - remainder);
333 list = g_slist_prepend(list, g_strstrip(column));
339 remainder = str + ctx->delimiter->len;
340 str = strstr(remainder, ctx->delimiter->str);
344 if (ctx->buffer->len && max_columns && n >= ctx->first_column) {
345 column = g_strdup(remainder);
346 list = g_slist_prepend(list, g_strstrip(column));
350 if (!(columns = g_try_new(char *, k + 1)))
355 for (l = list; l; l = l->next)
356 columns[k--] = l->data;
363 static int parse_multi_columns(char **columns, struct context *ctx)
367 /* Clear buffer in order to set bits only. */
368 memset(ctx->sample_buffer, 0, (ctx->num_channels + 7) >> 3);
370 for (i = 0; i < ctx->num_channels; i++) {
371 if (columns[i][0] == '1') {
372 ctx->sample_buffer[i / 8] |= (1 << (i % 8));
373 } else if (!strlen(columns[i])) {
374 sr_err("Column %zu in line %zu is empty.",
375 ctx->first_channel + i, ctx->line_number);
377 } else if (columns[i][0] != '0') {
378 sr_err("Invalid value '%s' in column %zu in line %zu.",
379 columns[i], ctx->first_channel + i,
388 static int parse_single_column(const char *column, struct context *ctx)
394 switch(ctx->format) {
396 res = parse_binstr(column, ctx);
399 res = parse_hexstr(column, ctx);
402 res = parse_octstr(column, ctx);
409 static int send_samples(const struct sr_dev_inst *sdi, uint8_t *buffer,
410 gsize buffer_size, gsize count)
413 struct sr_datafeed_packet packet;
414 struct sr_datafeed_logic logic;
417 packet.type = SR_DF_LOGIC;
418 packet.payload = &logic;
419 logic.unitsize = buffer_size;
420 logic.length = buffer_size;
423 for (i = 0; i < count; i++) {
424 if ((res = sr_session_send(sdi, &packet)) != SR_OK)
431 static int init(struct sr_input *in, const char *filename)
438 char channel_name[SR_MAX_CHANNELNAME_LEN + 1];
439 struct sr_channel *ch;
444 if (!(ctx = g_try_malloc0(sizeof(struct context)))) {
445 sr_err("Context malloc failed.");
446 return SR_ERR_MALLOC;
449 /* Create a virtual device. */
450 in->sdi = sr_dev_inst_new(0, SR_ST_ACTIVE, NULL, NULL, NULL);
453 /* Set default samplerate. */
457 * Enable auto-detection of the number of channels in multi column mode
458 * and enforce the specification of the number of channels in single
461 ctx->num_channels = 0;
463 /* Set default delimiter. */
464 if (!(ctx->delimiter = g_string_new(","))) {
465 sr_err("Delimiter malloc failed.");
467 return SR_ERR_MALLOC;
471 * Set default comment prefix. Note that an empty comment prefix
472 * disables removing of comments.
474 if (!(ctx->comment = g_string_new(""))) {
475 sr_err("Comment malloc failed.");
477 return SR_ERR_MALLOC;
480 /* Enable multi column mode by default. */
481 ctx->multi_column_mode = TRUE;
483 /* Use first column as default single column number. */
484 ctx->single_column = 0;
487 * In multi column mode start parsing sample data at the first column
488 * and in single column mode at the first bit.
490 ctx->first_channel = 0;
492 /* Start at the beginning of the file. */
495 /* Disable the usage of the first line as header by default. */
498 /* Set default format for single column mode. */
499 ctx->format = FORMAT_BIN;
501 if (!(ctx->buffer = g_string_new(""))) {
502 sr_err("Line buffer malloc failed.");
504 return SR_ERR_MALLOC;
508 if ((param = g_hash_table_lookup(in->param, "samplerate"))) {
509 res = sr_parse_sizestring(param, &ctx->samplerate);
512 sr_err("Invalid samplerate: %s.", param);
518 if ((param = g_hash_table_lookup(in->param, "numchannels")))
519 ctx->num_channels = g_ascii_strtoull(param, NULL, 10);
521 if ((param = g_hash_table_lookup(in->param, "delimiter"))) {
522 if (!strlen(param)) {
523 sr_err("Delimiter must be at least one character.");
528 if (!g_ascii_strcasecmp(param, "\\t"))
529 g_string_assign(ctx->delimiter, "\t");
531 g_string_assign(ctx->delimiter, param);
534 if ((param = g_hash_table_lookup(in->param, "comment")))
535 g_string_assign(ctx->comment, param);
537 if ((param = g_hash_table_lookup(in->param, "single-column"))) {
538 ctx->single_column = g_ascii_strtoull(param, &ptr, 10);
539 ctx->multi_column_mode = FALSE;
542 sr_err("Invalid single-colum number: %s.",
549 if ((param = g_hash_table_lookup(in->param, "first-channel")))
550 ctx->first_channel = g_ascii_strtoull(param, NULL, 10);
552 if ((param = g_hash_table_lookup(in->param, "startline"))) {
553 ctx->start_line = g_ascii_strtoull(param, NULL, 10);
555 if (ctx->start_line < 1) {
556 sr_err("Invalid start line: %s.", param);
562 if ((param = g_hash_table_lookup(in->param, "header")))
563 ctx->header = sr_parse_boolstring(param);
565 if ((param = g_hash_table_lookup(in->param, "format"))) {
566 if (!g_ascii_strncasecmp(param, "bin", 3)) {
567 ctx->format = FORMAT_BIN;
568 } else if (!g_ascii_strncasecmp(param, "hex", 3)) {
569 ctx->format = FORMAT_HEX;
570 } else if (!g_ascii_strncasecmp(param, "oct", 3)) {
571 ctx->format = FORMAT_OCT;
573 sr_err("Invalid format: %s.", param);
580 if (ctx->multi_column_mode)
581 ctx->first_column = ctx->first_channel;
583 ctx->first_column = ctx->single_column;
585 if (!ctx->multi_column_mode && !ctx->num_channels) {
586 sr_err("Number of channels needs to be specified in single column mode.");
591 if (!(ctx->channel = g_io_channel_new_file(filename, "r", NULL))) {
592 sr_err("Input file '%s' could not be opened.", filename);
599 status = g_io_channel_read_line_string(ctx->channel,
600 ctx->buffer, &term_pos, NULL);
602 if (status == G_IO_STATUS_EOF) {
603 sr_err("Input file is empty.");
608 if (status != G_IO_STATUS_NORMAL) {
609 sr_err("Error while reading line %zu.",
615 if (ctx->start_line > ctx->line_number) {
616 sr_spew("Line %zu skipped.", ctx->line_number);
620 /* Remove line termination character(s). */
621 g_string_truncate(ctx->buffer, term_pos);
623 if (!ctx->buffer->len) {
624 sr_spew("Blank line %zu skipped.", ctx->line_number);
628 /* Remove trailing comment. */
629 strip_comment(ctx->buffer, ctx->comment);
631 if (ctx->buffer->len)
634 sr_spew("Comment-only line %zu skipped.", ctx->line_number);
638 * In order to determine the number of columns parse the current line
639 * without limiting the number of columns.
641 if (!(columns = parse_line(ctx, -1))) {
642 sr_err("Error while parsing line %zu.", ctx->line_number);
647 num_columns = g_strv_length(columns);
649 /* Ensure that the first column is not out of bounds. */
651 sr_err("Column %zu in line %zu is out of bounds.",
652 ctx->first_column, ctx->line_number);
658 if (ctx->multi_column_mode) {
660 * Detect the number of channels in multi column mode
661 * automatically if not specified.
663 if (!ctx->num_channels) {
664 ctx->num_channels = num_columns;
665 sr_info("Number of auto-detected channels: %zu.",
670 * Ensure that the number of channels does not exceed the number
671 * of columns in multi column mode.
673 if (num_columns < ctx->num_channels) {
674 sr_err("Not enough columns for desired number of channels in line %zu.",
682 for (i = 0; i < ctx->num_channels; i++) {
683 if (ctx->header && ctx->multi_column_mode && strlen(columns[i]))
684 snprintf(channel_name, sizeof(channel_name), "%s",
687 snprintf(channel_name, sizeof(channel_name), "%zu", i);
689 ch = sr_channel_new(i, SR_CHANNEL_LOGIC, TRUE, channel_name);
692 sr_err("Channel creation failed.");
698 in->sdi->channels = g_slist_append(in->sdi->channels, ch);
704 * Calculate the minimum buffer size to store the sample data of the
707 ctx->sample_buffer_size = (ctx->num_channels + 7) >> 3;
709 if (!(ctx->sample_buffer = g_try_malloc(ctx->sample_buffer_size))) {
710 sr_err("Sample buffer malloc failed.");
712 return SR_ERR_MALLOC;
718 static int loadfile(struct sr_input *in, const char *filename)
722 struct sr_datafeed_packet packet;
723 struct sr_datafeed_meta meta;
724 struct sr_config *cfg;
726 gboolean read_new_line;
736 /* Send header packet to the session bus. */
737 std_session_send_df_header(in->sdi, LOG_PREFIX);
739 if (ctx->samplerate) {
740 packet.type = SR_DF_META;
741 packet.payload = &meta;
742 cfg = sr_config_new(SR_CONF_SAMPLERATE,
743 g_variant_new_uint64(ctx->samplerate));
744 meta.config = g_slist_append(NULL, cfg);
745 sr_session_send(in->sdi, &packet);
749 read_new_line = FALSE;
751 /* Limit the number of columns to parse. */
752 if (ctx->multi_column_mode)
753 max_columns = ctx->num_channels;
759 * Skip reading a new line for the first time if the last read
760 * line was not a header because the sample data is not parsed
763 if (read_new_line || ctx->header) {
765 status = g_io_channel_read_line_string(ctx->channel,
766 ctx->buffer, &term_pos, NULL);
768 if (status == G_IO_STATUS_EOF)
771 if (status != G_IO_STATUS_NORMAL) {
772 sr_err("Error while reading line %zu.",
778 /* Remove line termination character(s). */
779 g_string_truncate(ctx->buffer, term_pos);
782 read_new_line = TRUE;
784 if (!ctx->buffer->len) {
785 sr_spew("Blank line %zu skipped.", ctx->line_number);
789 /* Remove trailing comment. */
790 strip_comment(ctx->buffer, ctx->comment);
792 if (!ctx->buffer->len) {
793 sr_spew("Comment-only line %zu skipped.",
798 if (!(columns = parse_line(ctx, max_columns))) {
799 sr_err("Error while parsing line %zu.",
805 num_columns = g_strv_length(columns);
807 /* Ensure that the first column is not out of bounds. */
809 sr_err("Column %zu in line %zu is out of bounds.",
810 ctx->first_column, ctx->line_number);
817 * Ensure that the number of channels does not exceed the number
818 * of columns in multi column mode.
820 if (ctx->multi_column_mode && num_columns < ctx->num_channels) {
821 sr_err("Not enough columns for desired number of channels in line %zu.",
828 if (ctx->multi_column_mode)
829 res = parse_multi_columns(columns, ctx);
831 res = parse_single_column(columns[0], ctx);
842 * TODO: Parse sample numbers / timestamps and use it for
846 /* Send sample data to the session bus. */
847 res = send_samples(in->sdi, ctx->sample_buffer,
848 ctx->sample_buffer_size, 1);
851 sr_err("Sending samples failed.");
857 /* Send end packet to the session bus. */
858 packet.type = SR_DF_END;
859 sr_session_send(in->sdi, &packet);
866 SR_PRIV struct sr_input_module input_csv = {
868 .desc = "Comma-separated values (CSV)",
869 .format_match = format_match,
871 .loadfile = loadfile,