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/>.
24 #include <libsigrok/libsigrok.h>
25 #include "libsigrok-internal.h"
27 #define LOG_PREFIX "input/csv"
30 * The CSV input module has the following options:
32 * single-column: Specifies the column number which stores the sample data for
33 * single column mode and enables single column mode. Multi
34 * column mode is used if this parameter is omitted.
36 * numchannels: Specifies the number of channels to use. In multi column mode
37 * the number of channels are the number of columns and in single
38 * column mode the number of bits (LSB first) beginning at
41 * delimiter: Specifies the delimiter for columns. Must be at least one
42 * character. Comma is used as default delimiter.
44 * format: Specifies the format of the sample data in single column mode.
45 * Available formats are: 'bin', 'hex' and 'oct'. The binary
46 * format is used by default. This option has no effect in multi
49 * comment: Specifies the prefix character(s) for comments. No prefix
50 * characters are used by default which disables removing of
53 * samplerate: Samplerate which the sample data was captured with. Default
56 * first-channel: Column number of the first channel in multi column mode and
57 * position of the bit for the first channel in single column mode.
60 * header: Determines if the first line should be treated as header
61 * and used for channel names in multi column mode. Empty header
62 * names will be replaced by the channel number. If enabled in
63 * single column mode the first line will be skipped. Usage of
64 * header is disabled by default.
66 * startline: Line number to start processing sample data. Must be greater
67 * than 0. The default line number to start processing is 1.
73 * - Determine how the text line handling can get improved, regarding
74 * all of robustness and flexibility and correctness.
75 * - The current implementation splits on "any run of CR and LF". Which
76 * translates to: Line numbers are wrong in the presence of empty
77 * lines in the input stream.
78 * - The current implementation insists in the presence of end-of-line
79 * markers on _every_ line in the input stream. "Incomplete" text
80 * files that are so typical on the Windows platform get rejected as
82 * - Dropping support for CR style end-of-line markers could improve
83 * the situation a lot. Code could search for and split on LF, and
84 * trim optional trailing CR. This would result in proper support
85 * for CRLF (Windows) as well as LF (Unix), and allow for correct
87 * - When support for CR-only line termination cannot get dropped,
88 * then the current implementation is inappropriate. Currently the
89 * input stream is scanned for the first occurance of either of the
90 * supported termination styles (which is good). For the remaining
91 * session a consistent encoding of the text lines is assumed (which
92 * is acceptable). Potential absence of the terminator for the last
93 * line is orthogonal, and can get handled by a "force" flag when
94 * the end() routine calls the process_buffer() routine.
95 * - When line numbers need to be correct and reliable, _and_ the full
96 * set of previously supported line termination sequences are required,
97 * and potentially more are to get added for improved compatibility
98 * with more platforms or generators, then the current approach of
99 * splitting on runs of termination characters needs to get replaced,
100 * by the more expensive approach to scan for and count the initially
101 * determined termination sequence.
103 * - Add support for analog input data? (optional)
104 * - Needs a syntax first for user specs which channels (columns) are
105 * logic and which are analog. May need heuristics(?) to guess from
106 * input data in the absence of user provided specs.
109 /* Single column formats. */
119 /* Current selected samplerate. */
122 /* Number of channels. */
123 unsigned int num_channels;
125 /* Column delimiter character(s). */
128 /* Comment prefix character(s). */
131 /* Termination character(s) used in current stream. */
134 /* Determines if sample data is stored in multiple columns. */
135 gboolean multi_column_mode;
137 /* Column number of the sample data in single column mode. */
138 unsigned int single_column;
141 * Number of the first column to parse. Equivalent to the number of the
142 * first channel in multi column mode and the single column number in
143 * single column mode.
145 unsigned int first_column;
148 * Column number of the first channel in multi column mode and position of
149 * the bit for the first channel in single column mode.
151 unsigned int first_channel;
153 /* Line number to start processing. */
157 * Determines if the first line should be treated as header and used for
158 * channel names in multi column mode.
162 /* Format sample data is stored in single column mode. */
165 /* Size of the sample buffer. */
166 size_t sample_buffer_size;
168 /* Buffer to store sample data. */
169 uint8_t *sample_buffer;
171 /* Current line number. */
175 static void strip_comment(char *buf, const GString *prefix)
182 if ((ptr = strstr(buf, prefix->str)))
186 static int parse_binstr(const char *str, struct context *inc)
190 length = strlen(str);
193 sr_err("Column %u in line %zu is empty.", inc->single_column,
198 /* Clear buffer in order to set bits only. */
199 memset(inc->sample_buffer, 0, (inc->num_channels + 7) >> 3);
201 i = inc->first_channel;
203 for (j = 0; i < length && j < inc->num_channels; i++, j++) {
204 if (str[length - i - 1] == '1') {
205 inc->sample_buffer[j / 8] |= (1 << (j % 8));
206 } else if (str[length - i - 1] != '0') {
207 sr_err("Invalid value '%s' in column %u in line %zu.",
208 str, inc->single_column, inc->line_number);
216 static int parse_hexstr(const char *str, struct context *inc)
218 gsize i, j, k, length;
222 length = strlen(str);
225 sr_err("Column %u in line %zu is empty.", inc->single_column,
230 /* Clear buffer in order to set bits only. */
231 memset(inc->sample_buffer, 0, (inc->num_channels + 7) >> 3);
233 /* Calculate the position of the first hexadecimal digit. */
234 i = inc->first_channel / 4;
236 for (j = 0; i < length && j < inc->num_channels; i++) {
237 c = str[length - i - 1];
239 if (!g_ascii_isxdigit(c)) {
240 sr_err("Invalid value '%s' in column %u in line %zu.",
241 str, inc->single_column, inc->line_number);
245 value = g_ascii_xdigit_value(c);
247 k = (inc->first_channel + j) % 4;
249 for (; j < inc->num_channels && k < 4; k++) {
250 if (value & (1 << k))
251 inc->sample_buffer[j / 8] |= (1 << (j % 8));
260 static int parse_octstr(const char *str, struct context *inc)
262 gsize i, j, k, length;
266 length = strlen(str);
269 sr_err("Column %u in line %zu is empty.", inc->single_column,
274 /* Clear buffer in order to set bits only. */
275 memset(inc->sample_buffer, 0, (inc->num_channels + 7) >> 3);
277 /* Calculate the position of the first octal digit. */
278 i = inc->first_channel / 3;
280 for (j = 0; i < length && j < inc->num_channels; i++) {
281 c = str[length - i - 1];
283 if (c < '0' || c > '7') {
284 sr_err("Invalid value '%s' in column %u in line %zu.",
285 str, inc->single_column, inc->line_number);
289 value = g_ascii_xdigit_value(c);
291 k = (inc->first_channel + j) % 3;
293 for (; j < inc->num_channels && k < 3; k++) {
294 if (value & (1 << k))
295 inc->sample_buffer[j / 8] |= (1 << (j % 8));
304 static char **parse_line(char *buf, struct context *inc, int max_columns)
306 const char *str, *remainder;
317 str = strstr(remainder, inc->delimiter->str);
319 while (str && max_columns) {
320 if (n >= inc->first_column) {
321 column = g_strndup(remainder, str - remainder);
322 list = g_slist_prepend(list, g_strstrip(column));
328 remainder = str + inc->delimiter->len;
329 str = strstr(remainder, inc->delimiter->str);
333 if (buf[0] && max_columns && n >= inc->first_column) {
334 column = g_strdup(remainder);
335 list = g_slist_prepend(list, g_strstrip(column));
339 if (!(columns = g_try_new(char *, k + 1)))
344 for (l = list; l; l = l->next)
345 columns[k--] = l->data;
352 static int parse_multi_columns(char **columns, struct context *inc)
357 /* Clear buffer in order to set bits only. */
358 memset(inc->sample_buffer, 0, (inc->num_channels + 7) >> 3);
360 for (i = 0; i < inc->num_channels; i++) {
362 if (column[0] == '1') {
363 inc->sample_buffer[i / 8] |= (1 << (i % 8));
364 } else if (!strlen(column)) {
365 sr_err("Column %zu in line %zu is empty.",
366 inc->first_channel + i, inc->line_number);
368 } else if (column[0] != '0') {
369 sr_err("Invalid value '%s' in column %zu in line %zu.",
370 column, inc->first_channel + i,
379 static int parse_single_column(const char *column, struct context *inc)
385 switch (inc->format) {
387 res = parse_binstr(column, inc);
390 res = parse_hexstr(column, inc);
393 res = parse_octstr(column, inc);
400 static int send_samples(const struct sr_dev_inst *sdi, uint8_t *buffer,
401 gsize buffer_size, gsize count)
403 struct sr_datafeed_packet packet;
404 struct sr_datafeed_logic logic;
408 packet.type = SR_DF_LOGIC;
409 packet.payload = &logic;
410 logic.unitsize = buffer_size;
411 logic.length = buffer_size;
414 for (i = 0; i < count; i++) {
415 res = sr_session_send(sdi, &packet);
423 static int init(struct sr_input *in, GHashTable *options)
428 in->sdi = g_malloc0(sizeof(struct sr_dev_inst));
429 in->priv = inc = g_malloc0(sizeof(struct context));
431 inc->single_column = g_variant_get_int32(g_hash_table_lookup(options, "single-column"));
432 inc->multi_column_mode = inc->single_column == 0;
434 inc->num_channels = g_variant_get_int32(g_hash_table_lookup(options, "numchannels"));
436 inc->delimiter = g_string_new(g_variant_get_string(
437 g_hash_table_lookup(options, "delimiter"), NULL));
438 if (inc->delimiter->len == 0) {
439 sr_err("Delimiter must be at least one character.");
443 s = g_variant_get_string(g_hash_table_lookup(options, "format"), NULL);
444 if (!g_ascii_strncasecmp(s, "bin", 3)) {
445 inc->format = FORMAT_BIN;
446 } else if (!g_ascii_strncasecmp(s, "hex", 3)) {
447 inc->format = FORMAT_HEX;
448 } else if (!g_ascii_strncasecmp(s, "oct", 3)) {
449 inc->format = FORMAT_OCT;
451 sr_err("Invalid format: '%s'", s);
455 inc->comment = g_string_new(g_variant_get_string(
456 g_hash_table_lookup(options, "comment"), NULL));
457 if (g_string_equal(inc->comment, inc->delimiter)) {
458 /* That's never going to work. Likely the result of the user
459 * setting the delimiter to ; -- the default comment. Clearing
460 * the comment setting will work in that case. */
461 g_string_truncate(inc->comment, 0);
464 inc->samplerate = g_variant_get_uint64(g_hash_table_lookup(options, "samplerate"));
466 inc->first_channel = g_variant_get_int32(g_hash_table_lookup(options, "first-channel"));
468 inc->header = g_variant_get_boolean(g_hash_table_lookup(options, "header"));
470 inc->start_line = g_variant_get_int32(g_hash_table_lookup(options, "startline"));
471 if (inc->start_line < 1) {
472 sr_err("Invalid start line %zu.", inc->start_line);
476 if (inc->multi_column_mode)
477 inc->first_column = inc->first_channel;
479 inc->first_column = inc->single_column;
481 if (!inc->multi_column_mode && !inc->num_channels) {
482 sr_err("Number of channels needs to be specified in single column mode.");
489 static const char *delim_set = "\r\n";
491 static const char *get_line_termination(GString *buf)
496 if (g_strstr_len(buf->str, buf->len, "\r\n"))
498 else if (memchr(buf->str, '\n', buf->len))
500 else if (memchr(buf->str, '\r', buf->len))
506 static int initial_parse(const struct sr_input *in, GString *buf)
509 GString *channel_name;
510 unsigned int num_columns, i;
511 size_t line_number, l;
513 char **lines, *line, **columns, *column;
520 lines = g_strsplit_set(buf->str, delim_set, 0);
521 for (l = 0; lines[l]; l++) {
524 if (inc->start_line > line_number) {
525 sr_spew("Line %zu skipped.", line_number);
528 if (line[0] == '\0') {
529 sr_spew("Blank line %zu skipped.", line_number);
532 strip_comment(line, inc->comment);
533 if (line[0] == '\0') {
534 sr_spew("Comment-only line %zu skipped.", line_number);
538 /* Reached first proper line. */
542 /* Not enough data for a proper line yet. */
548 * In order to determine the number of columns parse the current line
549 * without limiting the number of columns.
551 columns = parse_line(line, inc, -1);
553 sr_err("Error while parsing line %zu.", line_number);
557 num_columns = g_strv_length(columns);
559 /* Ensure that the first column is not out of bounds. */
561 sr_err("Column %u in line %zu is out of bounds.",
562 inc->first_column, line_number);
567 if (inc->multi_column_mode) {
569 * Detect the number of channels in multi column mode
570 * automatically if not specified.
572 if (!inc->num_channels) {
573 inc->num_channels = num_columns;
574 sr_dbg("Number of auto-detected channels: %u.",
579 * Ensure that the number of channels does not exceed the number
580 * of columns in multi column mode.
582 if (num_columns < inc->num_channels) {
583 sr_err("Not enough columns for desired number of channels in line %zu.",
590 channel_name = g_string_sized_new(64);
591 for (i = 0; i < inc->num_channels; i++) {
593 if (inc->header && inc->multi_column_mode && column[0] != '\0')
594 g_string_assign(channel_name, column);
596 g_string_printf(channel_name, "%u", i);
597 sr_channel_new(in->sdi, i, SR_CHANNEL_LOGIC, TRUE, channel_name->str);
599 g_string_free(channel_name, TRUE);
602 * Calculate the minimum buffer size to store the sample data of the
605 inc->sample_buffer_size = (inc->num_channels + 7) >> 3;
606 inc->sample_buffer = g_malloc(inc->sample_buffer_size);
617 * Gets called from initial_receive(), which runs until the end-of-line
618 * encoding of the input stream could get determined. Assumes that this
619 * routine receives enough buffered initial input data to either see the
620 * BOM when there is one, or that no BOM will follow when a text line
621 * termination sequence was seen. Silently drops the UTF-8 BOM sequence
622 * from the input buffer if one was seen. Does not care to protect
623 * against multiple execution or dropping the BOM multiple times --
624 * there should be at most one in the input stream.
626 static void initial_bom_check(const struct sr_input *in)
628 static const char *utf8_bom = "\xef\xbb\xbf";
630 if (in->buf->len < strlen(utf8_bom))
632 if (strncmp(in->buf->str, utf8_bom, strlen(utf8_bom)) != 0)
634 g_string_erase(in->buf, 0, strlen(utf8_bom));
637 static int initial_receive(const struct sr_input *in)
643 const char *termination;
645 initial_bom_check(in);
649 termination = get_line_termination(in->buf);
651 /* Don't have a full line yet. */
654 p = g_strrstr_len(in->buf->str, in->buf->len, termination);
656 /* Don't have a full line yet. */
658 len = p - in->buf->str - 1;
659 new_buf = g_string_new_len(in->buf->str, len);
660 g_string_append_c(new_buf, '\0');
662 inc->termination = g_strdup(termination);
664 if (in->buf->str[0] != '\0')
665 ret = initial_parse(in, new_buf);
669 g_string_free(new_buf, TRUE);
674 static int process_buffer(struct sr_input *in)
676 struct sr_datafeed_packet packet;
677 struct sr_datafeed_meta meta;
678 struct sr_config *src;
682 int max_columns, ret, l;
683 char *p, **lines, *line, **columns;
687 std_session_send_df_header(in->sdi);
689 if (inc->samplerate) {
690 packet.type = SR_DF_META;
691 packet.payload = &meta;
692 samplerate = inc->samplerate;
693 src = sr_config_new(SR_CONF_SAMPLERATE, g_variant_new_uint64(samplerate));
694 meta.config = g_slist_append(NULL, src);
695 sr_session_send(in->sdi, &packet);
696 g_slist_free(meta.config);
703 /* Limit the number of columns to parse. */
704 if (inc->multi_column_mode)
705 max_columns = inc->num_channels;
710 * Consider empty input non-fatal. Keep accumulating input until
711 * at least one full text line has become available. Grab the
712 * maximum amount of accumulated data that consists of full text
713 * lines, and process what has been received so far, leaving not
714 * yet complete lines for the next invocation.
718 p = g_strrstr_len(in->buf->str, in->buf->len, inc->termination);
722 p += strlen(inc->termination);
723 g_strstrip(in->buf->str);
726 lines = g_strsplit_set(in->buf->str, delim_set, 0);
727 for (l = 0; lines[l]; l++) {
730 if (line[0] == '\0') {
731 sr_spew("Blank line %zu skipped.", inc->line_number);
735 /* Remove trailing comment. */
736 strip_comment(line, inc->comment);
737 if (line[0] == '\0') {
738 sr_spew("Comment-only line %zu skipped.", inc->line_number);
742 /* Skip the header line, its content was used as the channel names. */
744 sr_spew("Header line %zu skipped.", inc->line_number);
749 columns = parse_line(line, inc, max_columns);
751 sr_err("Error while parsing line %zu.", inc->line_number);
754 num_columns = g_strv_length(columns);
756 sr_err("Column %u in line %zu is out of bounds.",
757 inc->first_column, inc->line_number);
762 * Ensure that the number of channels does not exceed the number
763 * of columns in multi column mode.
765 if (inc->multi_column_mode && num_columns < inc->num_channels) {
766 sr_err("Not enough columns for desired number of channels in line %zu.",
772 if (inc->multi_column_mode)
773 ret = parse_multi_columns(columns, inc);
775 ret = parse_single_column(columns[0], inc);
781 /* Send sample data to the session bus. */
782 ret = send_samples(in->sdi, inc->sample_buffer,
783 inc->sample_buffer_size, 1);
785 sr_err("Sending samples failed.");
791 g_string_erase(in->buf, 0, p - in->buf->str);
796 static int receive(struct sr_input *in, GString *buf)
801 g_string_append_len(in->buf, buf->str, buf->len);
804 if (!inc->termination) {
805 ret = initial_receive(in);
806 if (ret == SR_ERR_NA)
807 /* Not enough data yet. */
809 else if (ret != SR_OK)
812 /* sdi is ready, notify frontend. */
813 in->sdi_ready = TRUE;
817 ret = process_buffer(in);
822 static int end(struct sr_input *in)
828 ret = process_buffer(in);
834 std_session_send_df_end(in->sdi);
839 static void cleanup(struct sr_input *in)
846 g_string_free(inc->delimiter, TRUE);
849 g_string_free(inc->comment, TRUE);
851 g_free(inc->termination);
852 g_free(inc->sample_buffer);
855 static int reset(struct sr_input *in)
857 struct context *inc = in->priv;
860 inc->started = FALSE;
861 g_string_truncate(in->buf, 0);
866 static struct sr_option options[] = {
867 { "single-column", "Single column", "Enable/specify single column", NULL, NULL },
868 { "numchannels", "Max channels", "Number of channels", NULL, NULL },
869 { "delimiter", "Delimiter", "Column delimiter", NULL, NULL },
870 { "format", "Format", "Numeric format", NULL, NULL },
871 { "comment", "Comment", "Comment prefix character", NULL, NULL },
872 { "samplerate", "Samplerate", "Samplerate used during capture", NULL, NULL },
873 { "first-channel", "First channel", "Column number of first channel", NULL, NULL },
874 { "header", "Header", "Treat first line as header with channel names", NULL, NULL },
875 { "startline", "Start line", "Line number at which to start processing samples", NULL, NULL },
879 static const struct sr_option *get_options(void)
881 if (!options[0].def) {
882 options[0].def = g_variant_ref_sink(g_variant_new_int32(0));
883 options[1].def = g_variant_ref_sink(g_variant_new_int32(0));
884 options[2].def = g_variant_ref_sink(g_variant_new_string(","));
885 options[3].def = g_variant_ref_sink(g_variant_new_string("bin"));
886 options[4].def = g_variant_ref_sink(g_variant_new_string(";"));
887 options[5].def = g_variant_ref_sink(g_variant_new_uint64(0));
888 options[6].def = g_variant_ref_sink(g_variant_new_int32(0));
889 options[7].def = g_variant_ref_sink(g_variant_new_boolean(FALSE));
890 options[8].def = g_variant_ref_sink(g_variant_new_int32(1));
896 SR_PRIV struct sr_input_module input_csv = {
899 .desc = "Comma-separated values",
900 .exts = (const char*[]){"csv", NULL},
901 .options = get_options,