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.
70 /* Single column formats. */
80 /* Current selected samplerate. */
83 /* Number of channels. */
84 unsigned int num_channels;
86 /* Column delimiter character(s). */
89 /* Comment prefix character(s). */
92 /* Termination character(s) used in current stream. */
95 /* Determines if sample data is stored in multiple columns. */
96 gboolean multi_column_mode;
98 /* Column number of the sample data in single column mode. */
99 unsigned int single_column;
102 * Number of the first column to parse. Equivalent to the number of the
103 * first channel in multi column mode and the single column number in
104 * single column mode.
106 unsigned int first_column;
109 * Column number of the first channel in multi column mode and position of
110 * the bit for the first channel in single column mode.
112 unsigned int first_channel;
114 /* Line number to start processing. */
118 * Determines if the first line should be treated as header and used for
119 * channel names in multi column mode.
123 /* Format sample data is stored in single column mode. */
126 /* Size of the sample buffer. */
127 size_t sample_buffer_size;
129 /* Buffer to store sample data. */
130 uint8_t *sample_buffer;
132 /* Current line number. */
136 static void strip_comment(char *buf, const GString *prefix)
143 if ((ptr = strstr(buf, prefix->str)))
147 static int parse_binstr(const char *str, struct context *inc)
151 length = strlen(str);
154 sr_err("Column %u in line %zu is empty.", inc->single_column,
159 /* Clear buffer in order to set bits only. */
160 memset(inc->sample_buffer, 0, (inc->num_channels + 7) >> 3);
162 i = inc->first_channel;
164 for (j = 0; i < length && j < inc->num_channels; i++, j++) {
165 if (str[length - i - 1] == '1') {
166 inc->sample_buffer[j / 8] |= (1 << (j % 8));
167 } else if (str[length - i - 1] != '0') {
168 sr_err("Invalid value '%s' in column %u in line %zu.",
169 str, inc->single_column, inc->line_number);
177 static int parse_hexstr(const char *str, struct context *inc)
179 gsize i, j, k, length;
183 length = strlen(str);
186 sr_err("Column %u in line %zu is empty.", inc->single_column,
191 /* Clear buffer in order to set bits only. */
192 memset(inc->sample_buffer, 0, (inc->num_channels + 7) >> 3);
194 /* Calculate the position of the first hexadecimal digit. */
195 i = inc->first_channel / 4;
197 for (j = 0; i < length && j < inc->num_channels; i++) {
198 c = str[length - i - 1];
200 if (!g_ascii_isxdigit(c)) {
201 sr_err("Invalid value '%s' in column %u in line %zu.",
202 str, inc->single_column, inc->line_number);
206 value = g_ascii_xdigit_value(c);
208 k = (inc->first_channel + j) % 4;
210 for (; j < inc->num_channels && k < 4; k++) {
211 if (value & (1 << k))
212 inc->sample_buffer[j / 8] |= (1 << (j % 8));
221 static int parse_octstr(const char *str, struct context *inc)
223 gsize i, j, k, length;
227 length = strlen(str);
230 sr_err("Column %u in line %zu is empty.", inc->single_column,
235 /* Clear buffer in order to set bits only. */
236 memset(inc->sample_buffer, 0, (inc->num_channels + 7) >> 3);
238 /* Calculate the position of the first octal digit. */
239 i = inc->first_channel / 3;
241 for (j = 0; i < length && j < inc->num_channels; i++) {
242 c = str[length - i - 1];
244 if (c < '0' || c > '7') {
245 sr_err("Invalid value '%s' in column %u in line %zu.",
246 str, inc->single_column, inc->line_number);
250 value = g_ascii_xdigit_value(c);
252 k = (inc->first_channel + j) % 3;
254 for (; j < inc->num_channels && k < 3; k++) {
255 if (value & (1 << k))
256 inc->sample_buffer[j / 8] |= (1 << (j % 8));
265 static char **parse_line(char *buf, struct context *inc, int max_columns)
267 const char *str, *remainder;
278 str = strstr(remainder, inc->delimiter->str);
280 while (str && max_columns) {
281 if (n >= inc->first_column) {
282 column = g_strndup(remainder, str - remainder);
283 list = g_slist_prepend(list, g_strstrip(column));
289 remainder = str + inc->delimiter->len;
290 str = strstr(remainder, inc->delimiter->str);
294 if (buf[0] && max_columns && n >= inc->first_column) {
295 column = g_strdup(remainder);
296 list = g_slist_prepend(list, g_strstrip(column));
300 if (!(columns = g_try_new(char *, k + 1)))
305 for (l = list; l; l = l->next)
306 columns[k--] = l->data;
313 static int parse_multi_columns(char **columns, struct context *inc)
317 /* Clear buffer in order to set bits only. */
318 memset(inc->sample_buffer, 0, (inc->num_channels + 7) >> 3);
320 for (i = 0; i < inc->num_channels; i++) {
321 if (columns[i][0] == '1') {
322 inc->sample_buffer[i / 8] |= (1 << (i % 8));
323 } else if (!strlen(columns[i])) {
324 sr_err("Column %zu in line %zu is empty.",
325 inc->first_channel + i, inc->line_number);
327 } else if (columns[i][0] != '0') {
328 sr_err("Invalid value '%s' in column %zu in line %zu.",
329 columns[i], inc->first_channel + i,
338 static int parse_single_column(const char *column, struct context *inc)
344 switch (inc->format) {
346 res = parse_binstr(column, inc);
349 res = parse_hexstr(column, inc);
352 res = parse_octstr(column, inc);
359 static int send_samples(const struct sr_dev_inst *sdi, uint8_t *buffer,
360 gsize buffer_size, gsize count)
362 struct sr_datafeed_packet packet;
363 struct sr_datafeed_logic logic;
367 packet.type = SR_DF_LOGIC;
368 packet.payload = &logic;
369 logic.unitsize = buffer_size;
370 logic.length = buffer_size;
373 for (i = 0; i < count; i++) {
374 if ((res = sr_session_send(sdi, &packet)) != SR_OK)
381 static int init(struct sr_input *in, GHashTable *options)
386 in->sdi = g_malloc0(sizeof(struct sr_dev_inst));
387 in->priv = inc = g_malloc0(sizeof(struct context));
389 inc->single_column = g_variant_get_int32(g_hash_table_lookup(options, "single-column"));
390 inc->multi_column_mode = inc->single_column == 0;
392 inc->num_channels = g_variant_get_int32(g_hash_table_lookup(options, "numchannels"));
394 inc->delimiter = g_string_new(g_variant_get_string(
395 g_hash_table_lookup(options, "delimiter"), NULL));
396 if (inc->delimiter->len == 0) {
397 sr_err("Delimiter must be at least one character.");
401 s = g_variant_get_string(g_hash_table_lookup(options, "format"), NULL);
402 if (!g_ascii_strncasecmp(s, "bin", 3)) {
403 inc->format = FORMAT_BIN;
404 } else if (!g_ascii_strncasecmp(s, "hex", 3)) {
405 inc->format = FORMAT_HEX;
406 } else if (!g_ascii_strncasecmp(s, "oct", 3)) {
407 inc->format = FORMAT_OCT;
409 sr_err("Invalid format: '%s'", s);
413 inc->comment = g_string_new(g_variant_get_string(
414 g_hash_table_lookup(options, "comment"), NULL));
415 if (g_string_equal(inc->comment, inc->delimiter)) {
416 /* That's never going to work. Likely the result of the user
417 * setting the delimiter to ; -- the default comment. Clearing
418 * the comment setting will work in that case. */
419 g_string_truncate(inc->comment, 0);
422 inc->samplerate = g_variant_get_uint64(g_hash_table_lookup(options, "samplerate"));
424 inc->first_channel = g_variant_get_int32(g_hash_table_lookup(options, "first-channel"));
426 inc->header = g_variant_get_boolean(g_hash_table_lookup(options, "header"));
428 inc->start_line = g_variant_get_int32(g_hash_table_lookup(options, "startline"));
429 if (inc->start_line < 1) {
430 sr_err("Invalid start line %zu.", inc->start_line);
434 if (inc->multi_column_mode)
435 inc->first_column = inc->first_channel;
437 inc->first_column = inc->single_column;
439 if (!inc->multi_column_mode && !inc->num_channels) {
440 sr_err("Number of channels needs to be specified in single column mode.");
447 static const char *get_line_termination(GString *buf)
452 if (g_strstr_len(buf->str, buf->len, "\r\n"))
454 else if (memchr(buf->str, '\n', buf->len))
456 else if (memchr(buf->str, '\r', buf->len))
462 static int initial_parse(const struct sr_input *in, GString *buf)
465 GString *channel_name;
466 unsigned int num_columns, i;
467 size_t line_number, l;
469 char **lines, **columns;
476 lines = g_strsplit_set(buf->str, "\r\n", 0);
477 for (l = 0; lines[l]; l++) {
479 if (inc->start_line > line_number) {
480 sr_spew("Line %zu skipped.", line_number);
483 if (lines[l][0] == '\0') {
484 sr_spew("Blank line %zu skipped.", line_number);
487 strip_comment(lines[l], inc->comment);
488 if (lines[l][0] == '\0') {
489 sr_spew("Comment-only line %zu skipped.", line_number);
493 /* Reached first proper line. */
497 /* Not enough data for a proper line yet. */
503 * In order to determine the number of columns parse the current line
504 * without limiting the number of columns.
506 if (!(columns = parse_line(lines[l], inc, -1))) {
507 sr_err("Error while parsing line %zu.", line_number);
511 num_columns = g_strv_length(columns);
513 /* Ensure that the first column is not out of bounds. */
515 sr_err("Column %u in line %zu is out of bounds.",
516 inc->first_column, line_number);
521 if (inc->multi_column_mode) {
523 * Detect the number of channels in multi column mode
524 * automatically if not specified.
526 if (!inc->num_channels) {
527 inc->num_channels = num_columns;
528 sr_dbg("Number of auto-detected channels: %u.",
533 * Ensure that the number of channels does not exceed the number
534 * of columns in multi column mode.
536 if (num_columns < inc->num_channels) {
537 sr_err("Not enough columns for desired number of channels in line %zu.",
544 channel_name = g_string_sized_new(64);
545 for (i = 0; i < inc->num_channels; i++) {
546 if (inc->header && inc->multi_column_mode && columns[i][0] != '\0')
547 g_string_assign(channel_name, columns[i]);
549 g_string_printf(channel_name, "%u", i);
550 sr_channel_new(in->sdi, i, SR_CHANNEL_LOGIC, TRUE, channel_name->str);
552 g_string_free(channel_name, TRUE);
555 * Calculate the minimum buffer size to store the sample data of the
558 inc->sample_buffer_size = (inc->num_channels + 7) >> 3;
559 inc->sample_buffer = g_malloc(inc->sample_buffer_size);
569 static int initial_receive(const struct sr_input *in)
575 const char *termination;
579 if (!(termination = get_line_termination(in->buf)))
580 /* Don't have a full line yet. */
583 if (!(p = g_strrstr_len(in->buf->str, in->buf->len, termination)))
584 /* Don't have a full line yet. */
586 len = p - in->buf->str - 1;
587 new_buf = g_string_new_len(in->buf->str, len);
588 g_string_append_c(new_buf, '\0');
590 inc->termination = g_strdup(termination);
592 if (in->buf->str[0] != '\0')
593 ret = initial_parse(in, new_buf);
597 g_string_free(new_buf, TRUE);
602 static int process_buffer(struct sr_input *in)
604 struct sr_datafeed_packet packet;
605 struct sr_datafeed_meta meta;
606 struct sr_config *src;
610 int max_columns, ret, l;
611 char *p, **lines, **columns;
615 std_session_send_df_header(in->sdi, LOG_PREFIX);
617 if (inc->samplerate) {
618 packet.type = SR_DF_META;
619 packet.payload = &meta;
620 samplerate = inc->samplerate;
621 src = sr_config_new(SR_CONF_SAMPLERATE, g_variant_new_uint64(samplerate));
622 meta.config = g_slist_append(NULL, src);
623 sr_session_send(in->sdi, &packet);
624 g_slist_free(meta.config);
631 if (!(p = g_strrstr_len(in->buf->str, in->buf->len, inc->termination)))
632 /* Don't have a full line. */
636 g_strstrip(in->buf->str);
638 /* Limit the number of columns to parse. */
639 if (inc->multi_column_mode)
640 max_columns = inc->num_channels;
645 lines = g_strsplit_set(in->buf->str, "\r\n", 0);
646 for (l = 0; lines[l]; l++) {
648 if (lines[l][0] == '\0') {
649 sr_spew("Blank line %zu skipped.", inc->line_number);
653 /* Remove trailing comment. */
654 strip_comment(lines[l], inc->comment);
655 if (lines[l][0] == '\0') {
656 sr_spew("Comment-only line %zu skipped.", inc->line_number);
660 /* Skip the header line, its content was used as the channel names. */
662 sr_spew("Header line %zu skipped.", inc->line_number);
667 if (!(columns = parse_line(lines[l], inc, max_columns))) {
668 sr_err("Error while parsing line %zu.", inc->line_number);
671 num_columns = g_strv_length(columns);
673 sr_err("Column %u in line %zu is out of bounds.",
674 inc->first_column, inc->line_number);
679 * Ensure that the number of channels does not exceed the number
680 * of columns in multi column mode.
682 if (inc->multi_column_mode && num_columns < inc->num_channels) {
683 sr_err("Not enough columns for desired number of channels in line %zu.",
689 if (inc->multi_column_mode)
690 ret = parse_multi_columns(columns, inc);
692 ret = parse_single_column(columns[0], inc);
698 /* Send sample data to the session bus. */
699 ret = send_samples(in->sdi, inc->sample_buffer,
700 inc->sample_buffer_size, 1);
702 sr_err("Sending samples failed.");
708 g_string_erase(in->buf, 0, p - in->buf->str + 1);
713 static int receive(struct sr_input *in, GString *buf)
718 g_string_append_len(in->buf, buf->str, buf->len);
721 if (!inc->termination) {
722 if ((ret = initial_receive(in)) == SR_ERR_NA)
723 /* Not enough data yet. */
725 else if (ret != SR_OK)
728 /* sdi is ready, notify frontend. */
729 in->sdi_ready = TRUE;
733 ret = process_buffer(in);
738 static int end(struct sr_input *in)
741 struct sr_datafeed_packet packet;
745 ret = process_buffer(in);
752 packet.type = SR_DF_END;
753 sr_session_send(in->sdi, &packet);
759 static void cleanup(struct sr_input *in)
766 g_string_free(inc->delimiter, TRUE);
769 g_string_free(inc->comment, TRUE);
771 g_free(inc->termination);
772 g_free(inc->sample_buffer);
775 static struct sr_option options[] = {
776 { "single-column", "Single column", "Enable/specify single column", NULL, NULL },
777 { "numchannels", "Max channels", "Number of channels", NULL, NULL },
778 { "delimiter", "Delimiter", "Column delimiter", NULL, NULL },
779 { "format", "Format", "Numeric format", NULL, NULL },
780 { "comment", "Comment", "Comment prefix character", NULL, NULL },
781 { "samplerate", "Samplerate", "Samplerate used during capture", NULL, NULL },
782 { "first-channel", "First channel", "Column number of first channel", NULL, NULL },
783 { "header", "Header", "Treat first line as header with channel names", NULL, NULL },
784 { "startline", "Start line", "Line number at which to start processing samples", NULL, NULL },
788 static const struct sr_option *get_options(void)
790 if (!options[0].def) {
791 options[0].def = g_variant_ref_sink(g_variant_new_int32(0));
792 options[1].def = g_variant_ref_sink(g_variant_new_int32(0));
793 options[2].def = g_variant_ref_sink(g_variant_new_string(","));
794 options[3].def = g_variant_ref_sink(g_variant_new_string("bin"));
795 options[4].def = g_variant_ref_sink(g_variant_new_string(";"));
796 options[5].def = g_variant_ref_sink(g_variant_new_uint64(0));
797 options[6].def = g_variant_ref_sink(g_variant_new_int32(0));
798 options[7].def = g_variant_ref_sink(g_variant_new_boolean(FALSE));
799 options[8].def = g_variant_ref_sink(g_variant_new_int32(1));
805 SR_PRIV struct sr_input_module input_csv = {
808 .desc = "Comma-separated values",
809 .exts = (const char*[]){"csv", NULL},
810 .options = get_options,