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. */
79 /* Current selected samplerate. */
82 /* Number of channels. */
85 /* Column delimiter character(s). */
88 /* Comment prefix character(s). */
91 /* Termination character(s) used in current stream. */
94 /* Determines if sample data is stored in multiple columns. */
95 gboolean multi_column_mode;
97 /* Column number of the sample data in single column mode. */
101 * Number of the first column to parse. Equivalent to the number of the
102 * first channel in multi column mode and the single column number in
103 * single column mode.
108 * Column number of the first channel in multi column mode and position of
109 * the bit for the first channel in single column mode.
113 /* Line number to start processing. */
117 * Determines if the first line should be treated as header and used for
118 * channel names in multi column mode.
122 /* Format sample data is stored in single column mode. */
125 /* Size of the sample buffer. */
126 gsize sample_buffer_size;
128 /* Buffer to store sample data. */
129 uint8_t *sample_buffer;
131 /* Current line number. */
135 static int format_match(GHashTable *metadata)
139 buf = g_hash_table_lookup(metadata, GINT_TO_POINTER(SR_INPUT_META_MIMETYPE));
140 if (!strcmp(buf, "text/csv"))
146 static void strip_comment(char *buf, const GString *prefix)
153 if ((ptr = strstr(buf, prefix->str)))
157 static int parse_binstr(const char *str, struct context *inc)
161 length = strlen(str);
164 sr_err("Column %zu in line %zu is empty.", inc->single_column,
169 /* Clear buffer in order to set bits only. */
170 memset(inc->sample_buffer, 0, (inc->num_channels + 7) >> 3);
172 i = inc->first_channel;
174 for (j = 0; i < length && j < inc->num_channels; i++, j++) {
175 if (str[length - i - 1] == '1') {
176 inc->sample_buffer[j / 8] |= (1 << (j % 8));
177 } else if (str[length - i - 1] != '0') {
178 sr_err("Invalid value '%s' in column %zu in line %zu.",
179 str, inc->single_column, inc->line_number);
187 static int parse_hexstr(const char *str, struct context *inc)
189 gsize i, j, k, length;
193 length = strlen(str);
196 sr_err("Column %zu in line %zu is empty.", inc->single_column,
201 /* Clear buffer in order to set bits only. */
202 memset(inc->sample_buffer, 0, (inc->num_channels + 7) >> 3);
204 /* Calculate the position of the first hexadecimal digit. */
205 i = inc->first_channel / 4;
207 for (j = 0; i < length && j < inc->num_channels; i++) {
208 c = str[length - i - 1];
210 if (!g_ascii_isxdigit(c)) {
211 sr_err("Invalid value '%s' in column %zu in line %zu.",
212 str, inc->single_column, inc->line_number);
216 value = g_ascii_xdigit_value(c);
218 k = (inc->first_channel + j) % 4;
220 for (; j < inc->num_channels && k < 4; k++) {
221 if (value & (1 << k))
222 inc->sample_buffer[j / 8] |= (1 << (j % 8));
231 static int parse_octstr(const char *str, struct context *inc)
233 gsize i, j, k, length;
237 length = strlen(str);
240 sr_err("Column %zu in line %zu is empty.", inc->single_column,
245 /* Clear buffer in order to set bits only. */
246 memset(inc->sample_buffer, 0, (inc->num_channels + 7) >> 3);
248 /* Calculate the position of the first octal digit. */
249 i = inc->first_channel / 3;
251 for (j = 0; i < length && j < inc->num_channels; i++) {
252 c = str[length - i - 1];
254 if (c < '0' || c > '7') {
255 sr_err("Invalid value '%s' in column %zu in line %zu.",
256 str, inc->single_column, inc->line_number);
260 value = g_ascii_xdigit_value(c);
262 k = (inc->first_channel + j) % 3;
264 for (; j < inc->num_channels && k < 3; k++) {
265 if (value & (1 << k))
266 inc->sample_buffer[j / 8] |= (1 << (j % 8));
275 static char **parse_line(char *buf, struct context *inc, int max_columns)
277 const char *str, *remainder;
288 str = strstr(remainder, inc->delimiter->str);
290 while (str && max_columns) {
291 if (n >= inc->first_column) {
292 column = g_strndup(remainder, str - remainder);
293 list = g_slist_prepend(list, g_strstrip(column));
299 remainder = str + inc->delimiter->len;
300 str = strstr(remainder, inc->delimiter->str);
304 if (buf[0] && max_columns && n >= inc->first_column) {
305 column = g_strdup(remainder);
306 list = g_slist_prepend(list, g_strstrip(column));
310 if (!(columns = g_try_new(char *, k + 1)))
315 for (l = list; l; l = l->next)
316 columns[k--] = l->data;
323 static int parse_multi_columns(char **columns, struct context *inc)
327 /* Clear buffer in order to set bits only. */
328 memset(inc->sample_buffer, 0, (inc->num_channels + 7) >> 3);
330 for (i = 0; i < inc->num_channels; i++) {
331 if (columns[i][0] == '1') {
332 inc->sample_buffer[i / 8] |= (1 << (i % 8));
333 } else if (!strlen(columns[i])) {
334 sr_err("Column %zu in line %zu is empty.",
335 inc->first_channel + i, inc->line_number);
337 } else if (columns[i][0] != '0') {
338 sr_err("Invalid value '%s' in column %zu in line %zu.",
339 columns[i], inc->first_channel + i,
348 static int parse_single_column(const char *column, struct context *inc)
354 switch(inc->format) {
356 res = parse_binstr(column, inc);
359 res = parse_hexstr(column, inc);
362 res = parse_octstr(column, inc);
369 static int send_samples(const struct sr_dev_inst *sdi, uint8_t *buffer,
370 gsize buffer_size, gsize count)
372 struct sr_datafeed_packet packet;
373 struct sr_datafeed_logic logic;
377 packet.type = SR_DF_LOGIC;
378 packet.payload = &logic;
379 logic.unitsize = buffer_size;
380 logic.length = buffer_size;
383 for (i = 0; i < count; i++) {
384 if ((res = sr_session_send(sdi, &packet)) != SR_OK)
391 static int init(struct sr_input *in, GHashTable *options)
396 in->sdi = g_malloc0(sizeof(struct sr_dev_inst));
397 in->priv = inc = g_malloc0(sizeof(struct context));
399 inc->single_column = g_variant_get_int32(g_hash_table_lookup(options, "single-column"));
400 inc->multi_column_mode = inc->single_column == 0;
402 inc->num_channels = g_variant_get_int32(g_hash_table_lookup(options, "numchannels"));
404 inc->delimiter = g_string_new(g_variant_get_string(
405 g_hash_table_lookup(options, "delimiter"), NULL));
406 if (inc->delimiter->len == 0) {
407 sr_err("Delimiter must be at least one character.");
411 s = g_variant_get_string(g_hash_table_lookup(options, "format"), NULL);
412 if (!g_ascii_strncasecmp(s, "bin", 3)) {
413 inc->format = FORMAT_BIN;
414 } else if (!g_ascii_strncasecmp(s, "hex", 3)) {
415 inc->format = FORMAT_HEX;
416 } else if (!g_ascii_strncasecmp(s, "oct", 3)) {
417 inc->format = FORMAT_OCT;
419 sr_err("Invalid format: '%s'", s);
423 inc->comment = g_string_new(g_variant_get_string(
424 g_hash_table_lookup(options, "comment"), NULL));
425 if (g_string_equal(inc->comment, inc->delimiter)) {
426 /* That's never going to work. Likely the result of the user
427 * setting the delimiter to ; -- the default comment. Clearing
428 * the comment setting will work in that case. */
429 g_string_truncate(inc->comment, 0);
432 inc->samplerate = g_variant_get_uint64(g_hash_table_lookup(options, "samplerate"));
434 inc->first_channel = g_variant_get_int32(g_hash_table_lookup(options, "first-channel"));
436 inc->header = g_variant_get_boolean(g_hash_table_lookup(options, "header"));
438 inc->start_line = g_variant_get_int32(g_hash_table_lookup(options, "startline"));
439 if (inc->start_line < 1) {
440 sr_err("Invalid start line %d.", inc->start_line);
444 if (inc->multi_column_mode)
445 inc->first_column = inc->first_channel;
447 inc->first_column = inc->single_column;
449 if (!inc->multi_column_mode && !inc->num_channels) {
450 sr_err("Number of channels needs to be specified in single column mode.");
457 static char *get_line_termination(GString *buf)
462 if (g_strstr_len(buf->str, buf->len, "\r\n"))
464 else if (memchr(buf->str, '\n', buf->len))
466 else if (memchr(buf->str, '\r', buf->len))
472 static int initial_parse(const struct sr_input *in, GString *buf)
475 struct sr_channel *ch;
476 GString *channel_name;
477 gsize num_columns, l, i;
478 unsigned int line_number;
480 char **lines, **columns;
487 lines = g_strsplit_set(buf->str, "\r\n", 0);
488 for (l = 0; lines[l]; l++) {
490 if (inc->start_line > line_number) {
491 sr_spew("Line %zu skipped.", line_number);
494 if (lines[l][0] == '\0') {
495 sr_spew("Blank line %zu skipped.", line_number);
498 strip_comment(lines[l], inc->comment);
499 if (lines[l][0] == '\0') {
500 sr_spew("Comment-only line %zu skipped.", line_number);
504 /* Reached first proper line. */
508 /* Not enough data for a proper line yet. */
514 * In order to determine the number of columns parse the current line
515 * without limiting the number of columns.
517 if (!(columns = parse_line(lines[l], inc, -1))) {
518 sr_err("Error while parsing line %zu.", line_number);
522 num_columns = g_strv_length(columns);
524 /* Ensure that the first column is not out of bounds. */
526 sr_err("Column %zu in line %zu is out of bounds.",
527 inc->first_column, line_number);
532 if (inc->multi_column_mode) {
534 * Detect the number of channels in multi column mode
535 * automatically if not specified.
537 if (!inc->num_channels) {
538 inc->num_channels = num_columns;
539 sr_dbg("Number of auto-detected channels: %zu.",
544 * Ensure that the number of channels does not exceed the number
545 * of columns in multi column mode.
547 if (num_columns < inc->num_channels) {
548 sr_err("Not enough columns for desired number of channels in line %zu.",
555 channel_name = g_string_sized_new(64);
556 for (i = 0; i < inc->num_channels; i++) {
557 if (inc->header && inc->multi_column_mode && strlen(columns[i]))
558 g_string_assign(channel_name, columns[i]);
560 g_string_printf(channel_name, "%zu", i);
561 ch = sr_channel_new(i, SR_CHANNEL_LOGIC, TRUE, channel_name->str);
562 in->sdi->channels = g_slist_append(in->sdi->channels, ch);
564 g_string_free(channel_name, TRUE);
567 * Calculate the minimum buffer size to store the sample data of the
570 inc->sample_buffer_size = (inc->num_channels + 7) >> 3;
571 inc->sample_buffer = g_malloc(inc->sample_buffer_size);
581 static int initial_receive(const struct sr_input *in)
586 char *termination, *p;
590 if (!(termination = get_line_termination(in->buf)))
591 /* Don't have a full line yet. */
594 if (!(p = g_strrstr_len(in->buf->str, in->buf->len, termination)))
595 /* Don't have a full line yet. */
597 len = p - in->buf->str - 1;
598 new_buf = g_string_new_len(in->buf->str, len);
599 g_string_append_c(new_buf, '\0');
601 inc->termination = g_strdup(termination);
603 if (in->buf->str[0] != '\0')
604 ret = initial_parse(in, new_buf);
608 g_string_free(new_buf, TRUE);
613 static int process_buffer(struct sr_input *in)
615 struct sr_datafeed_packet packet;
616 struct sr_datafeed_meta meta;
617 struct sr_config *src;
621 int max_columns, ret, l;
622 char *p, **lines, **columns;
626 std_session_send_df_header(in->sdi, LOG_PREFIX);
628 if (inc->samplerate) {
629 packet.type = SR_DF_META;
630 packet.payload = &meta;
631 samplerate = inc->samplerate;
632 src = sr_config_new(SR_CONF_SAMPLERATE, g_variant_new_uint64(samplerate));
633 meta.config = g_slist_append(NULL, src);
634 sr_session_send(in->sdi, &packet);
641 if (!(p = g_strrstr_len(in->buf->str, in->buf->len, inc->termination)))
642 /* Don't have a full line. */
646 g_strstrip(in->buf->str);
648 /* Limit the number of columns to parse. */
649 if (inc->multi_column_mode)
650 max_columns = inc->num_channels;
655 lines = g_strsplit_set(in->buf->str, "\r\n", 0);
656 for (l = 0; lines[l]; l++) {
658 if (lines[l][0] == '\0') {
659 sr_spew("Blank line %zu skipped.", inc->line_number);
663 /* Remove trailing comment. */
664 strip_comment(lines[l], inc->comment);
665 if (lines[l][0] == '\0') {
666 sr_spew("Comment-only line %zu skipped.", inc->line_number);
670 /* Skip the header line, its content was used as the channel names. */
672 sr_spew("Header line %zu skipped.", inc->line_number);
677 if (!(columns = parse_line(lines[l], inc, max_columns))) {
678 sr_err("Error while parsing line %zu.", inc->line_number);
681 num_columns = g_strv_length(columns);
683 sr_err("Column %zu in line %zu is out of bounds.",
684 inc->first_column, inc->line_number);
689 * Ensure that the number of channels does not exceed the number
690 * of columns in multi column mode.
692 if (inc->multi_column_mode && num_columns < inc->num_channels) {
693 sr_err("Not enough columns for desired number of channels in line %zu.",
699 if (inc->multi_column_mode)
700 ret = parse_multi_columns(columns, inc);
702 ret = parse_single_column(columns[0], inc);
708 /* Send sample data to the session bus. */
709 ret = send_samples(in->sdi, inc->sample_buffer,
710 inc->sample_buffer_size, 1);
712 sr_err("Sending samples failed.");
718 g_string_erase(in->buf, 0, p - in->buf->str + 1);
723 static int receive(struct sr_input *in, GString *buf)
728 g_string_append_len(in->buf, buf->str, buf->len);
731 if (!inc->termination) {
732 if ((ret = initial_receive(in)) == SR_ERR_NA)
733 /* Not enough data yet. */
735 else if (ret != SR_OK)
738 /* sdi is ready, notify frontend. */
739 in->sdi_ready = TRUE;
743 ret = process_buffer(in);
748 static int end(struct sr_input *in)
751 struct sr_datafeed_packet packet;
755 ret = process_buffer(in);
762 packet.type = SR_DF_END;
763 sr_session_send(in->sdi, &packet);
769 static void cleanup(struct sr_input *in)
776 g_string_free(inc->delimiter, TRUE);
779 g_string_free(inc->comment, TRUE);
781 if (inc->termination)
782 g_free(inc->termination);
784 if (inc->sample_buffer)
785 g_free(inc->sample_buffer);
788 static struct sr_option options[] = {
789 { "single-column", "Single column", "Enable/specify single column", NULL, NULL },
790 { "numchannels", "Max channels", "Number of channels", NULL, NULL },
791 { "delimiter", "Delimiter", "Column delimiter", NULL, NULL },
792 { "format", "Format", "Numeric format", NULL, NULL },
793 { "comment", "Comment", "Comment prefix character", NULL, NULL },
794 { "samplerate", "Samplerate", "Samplerate used during capture", NULL, NULL },
795 { "first-channel", "First channel", "Column number of first channel", NULL, NULL },
796 { "header", "Header", "Treat first line as header with channel names", NULL, NULL },
797 { "startline", "Start line", "Line number at which to start processing samples", NULL, NULL },
801 static struct sr_option *get_options(void)
803 if (!options[0].def) {
804 options[0].def = g_variant_ref_sink(g_variant_new_int32(0));
805 options[1].def = g_variant_ref_sink(g_variant_new_int32(0));
806 options[2].def = g_variant_ref_sink(g_variant_new_string(","));
807 options[3].def = g_variant_ref_sink(g_variant_new_string("bin"));
808 options[4].def = g_variant_ref_sink(g_variant_new_string(";"));
809 options[5].def = g_variant_ref_sink(g_variant_new_uint64(0));
810 options[6].def = g_variant_ref_sink(g_variant_new_int32(0));
811 options[7].def = g_variant_ref_sink(g_variant_new_boolean(FALSE));
812 options[8].def = g_variant_ref_sink(g_variant_new_int32(1));
818 SR_PRIV struct sr_input_module input_csv = {
821 .desc = "Comma-separated values",
822 .metadata = { SR_INPUT_META_MIMETYPE },
823 .options = get_options,
824 .format_match = format_match,