]> sigrok.org Git - libsigrok.git/blame - src/input/csv.c
input/csv: Accept absence of last end-of-line termination sequence
[libsigrok.git] / src / input / csv.c
CommitLineData
4a35548b
MS
1/*
2 * This file is part of the libsigrok project.
3 *
4 * Copyright (C) 2013 Marc Schink <sigrok-dev@marcschink.de>
5 *
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.
10 *
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.
15 *
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/>.
18 */
19
6ec6c43b 20#include <config.h>
4a35548b
MS
21#include <stdlib.h>
22#include <string.h>
23#include <glib.h>
c1aae900 24#include <libsigrok/libsigrok.h>
4a35548b
MS
25#include "libsigrok-internal.h"
26
3544f848 27#define LOG_PREFIX "input/csv"
4a35548b
MS
28
29/*
30 * The CSV input module has the following options:
31 *
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.
35 *
ba7dd8bb
UH
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
4a35548b 38 * column mode the number of bits (LSB first) beginning at
ba7dd8bb 39 * 'first-channel'.
4a35548b
MS
40 *
41 * delimiter: Specifies the delimiter for columns. Must be at least one
42 * character. Comma is used as default delimiter.
43 *
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
47 * column mode.
48 *
49 * comment: Specifies the prefix character(s) for comments. No prefix
50 * characters are used by default which disables removing of
51 * comments.
52 *
53 * samplerate: Samplerate which the sample data was captured with. Default
54 * value is 0.
55 *
ba7dd8bb
UH
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.
4a35548b
MS
58 * Default value is 0.
59 *
60 * header: Determines if the first line should be treated as header
ba7dd8bb
UH
61 * and used for channel names in multi column mode. Empty header
62 * names will be replaced by the channel number. If enabled in
4a35548b
MS
63 * single column mode the first line will be skipped. Usage of
64 * header is disabled by default.
65 *
66 * startline: Line number to start processing sample data. Must be greater
67 * than 0. The default line number to start processing is 1.
68 */
69
ccff468b
GS
70/*
71 * TODO
72 *
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
81 * invalid.
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
86 * line number counts.
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.
102 *
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.
107 */
108
4a35548b
MS
109/* Single column formats. */
110enum {
111 FORMAT_BIN,
112 FORMAT_HEX,
113 FORMAT_OCT
114};
115
116struct context {
41d214f6
BV
117 gboolean started;
118
4a35548b
MS
119 /* Current selected samplerate. */
120 uint64_t samplerate;
121
ba7dd8bb 122 /* Number of channels. */
6433156c 123 unsigned int num_channels;
4a35548b
MS
124
125 /* Column delimiter character(s). */
126 GString *delimiter;
127
128 /* Comment prefix character(s). */
129 GString *comment;
130
d9251a2c 131 /* Termination character(s) used in current stream. */
41d214f6
BV
132 char *termination;
133
4a35548b
MS
134 /* Determines if sample data is stored in multiple columns. */
135 gboolean multi_column_mode;
136
137 /* Column number of the sample data in single column mode. */
6433156c 138 unsigned int single_column;
4a35548b
MS
139
140 /*
141 * Number of the first column to parse. Equivalent to the number of the
ba7dd8bb 142 * first channel in multi column mode and the single column number in
4a35548b
MS
143 * single column mode.
144 */
6433156c 145 unsigned int first_column;
4a35548b
MS
146
147 /*
ba7dd8bb
UH
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.
4a35548b 150 */
6433156c 151 unsigned int first_channel;
4a35548b
MS
152
153 /* Line number to start processing. */
6433156c 154 size_t start_line;
4a35548b
MS
155
156 /*
157 * Determines if the first line should be treated as header and used for
ba7dd8bb 158 * channel names in multi column mode.
4a35548b
MS
159 */
160 gboolean header;
161
162 /* Format sample data is stored in single column mode. */
163 int format;
164
165 /* Size of the sample buffer. */
6433156c 166 size_t sample_buffer_size;
4a35548b
MS
167
168 /* Buffer to store sample data. */
169 uint8_t *sample_buffer;
170
4a35548b 171 /* Current line number. */
6433156c 172 size_t line_number;
4a35548b
MS
173};
174
41d214f6 175static void strip_comment(char *buf, const GString *prefix)
4a35548b
MS
176{
177 char *ptr;
178
179 if (!prefix->len)
180 return;
181
41d214f6
BV
182 if ((ptr = strstr(buf, prefix->str)))
183 *ptr = '\0';
4a35548b
MS
184}
185
41d214f6 186static int parse_binstr(const char *str, struct context *inc)
4a35548b
MS
187{
188 gsize i, j, length;
189
190 length = strlen(str);
191
192 if (!length) {
6433156c 193 sr_err("Column %u in line %zu is empty.", inc->single_column,
41d214f6 194 inc->line_number);
4a35548b
MS
195 return SR_ERR;
196 }
197
198 /* Clear buffer in order to set bits only. */
41d214f6 199 memset(inc->sample_buffer, 0, (inc->num_channels + 7) >> 3);
4a35548b 200
41d214f6 201 i = inc->first_channel;
4a35548b 202
41d214f6 203 for (j = 0; i < length && j < inc->num_channels; i++, j++) {
4a35548b 204 if (str[length - i - 1] == '1') {
41d214f6 205 inc->sample_buffer[j / 8] |= (1 << (j % 8));
4a35548b 206 } else if (str[length - i - 1] != '0') {
6433156c 207 sr_err("Invalid value '%s' in column %u in line %zu.",
41d214f6 208 str, inc->single_column, inc->line_number);
4a35548b
MS
209 return SR_ERR;
210 }
211 }
212
213 return SR_OK;
214}
215
41d214f6 216static int parse_hexstr(const char *str, struct context *inc)
4a35548b
MS
217{
218 gsize i, j, k, length;
219 uint8_t value;
220 char c;
221
222 length = strlen(str);
223
224 if (!length) {
6433156c 225 sr_err("Column %u in line %zu is empty.", inc->single_column,
41d214f6 226 inc->line_number);
4a35548b
MS
227 return SR_ERR;
228 }
229
230 /* Clear buffer in order to set bits only. */
41d214f6 231 memset(inc->sample_buffer, 0, (inc->num_channels + 7) >> 3);
4a35548b
MS
232
233 /* Calculate the position of the first hexadecimal digit. */
41d214f6 234 i = inc->first_channel / 4;
4a35548b 235
41d214f6 236 for (j = 0; i < length && j < inc->num_channels; i++) {
4a35548b
MS
237 c = str[length - i - 1];
238
239 if (!g_ascii_isxdigit(c)) {
6433156c 240 sr_err("Invalid value '%s' in column %u in line %zu.",
41d214f6 241 str, inc->single_column, inc->line_number);
4a35548b
MS
242 return SR_ERR;
243 }
244
245 value = g_ascii_xdigit_value(c);
246
41d214f6 247 k = (inc->first_channel + j) % 4;
4a35548b 248
41d214f6 249 for (; j < inc->num_channels && k < 4; k++) {
4a35548b 250 if (value & (1 << k))
41d214f6 251 inc->sample_buffer[j / 8] |= (1 << (j % 8));
4a35548b
MS
252
253 j++;
254 }
255 }
256
257 return SR_OK;
258}
259
41d214f6 260static int parse_octstr(const char *str, struct context *inc)
4a35548b
MS
261{
262 gsize i, j, k, length;
263 uint8_t value;
264 char c;
265
266 length = strlen(str);
267
268 if (!length) {
6433156c 269 sr_err("Column %u in line %zu is empty.", inc->single_column,
41d214f6 270 inc->line_number);
4a35548b
MS
271 return SR_ERR;
272 }
273
274 /* Clear buffer in order to set bits only. */
41d214f6 275 memset(inc->sample_buffer, 0, (inc->num_channels + 7) >> 3);
4a35548b
MS
276
277 /* Calculate the position of the first octal digit. */
41d214f6 278 i = inc->first_channel / 3;
4a35548b 279
41d214f6 280 for (j = 0; i < length && j < inc->num_channels; i++) {
4a35548b
MS
281 c = str[length - i - 1];
282
283 if (c < '0' || c > '7') {
6433156c 284 sr_err("Invalid value '%s' in column %u in line %zu.",
41d214f6 285 str, inc->single_column, inc->line_number);
4a35548b
MS
286 return SR_ERR;
287 }
288
289 value = g_ascii_xdigit_value(c);
290
41d214f6 291 k = (inc->first_channel + j) % 3;
4a35548b 292
41d214f6 293 for (; j < inc->num_channels && k < 3; k++) {
4a35548b 294 if (value & (1 << k))
41d214f6 295 inc->sample_buffer[j / 8] |= (1 << (j % 8));
4a35548b
MS
296
297 j++;
298 }
299 }
300
301 return SR_OK;
302}
303
41d214f6 304static char **parse_line(char *buf, struct context *inc, int max_columns)
4a35548b
MS
305{
306 const char *str, *remainder;
307 GSList *list, *l;
308 char **columns;
309 char *column;
310 gsize n, k;
311
312 n = 0;
313 k = 0;
314 list = NULL;
315
41d214f6
BV
316 remainder = buf;
317 str = strstr(remainder, inc->delimiter->str);
4a35548b
MS
318
319 while (str && max_columns) {
41d214f6 320 if (n >= inc->first_column) {
4a35548b
MS
321 column = g_strndup(remainder, str - remainder);
322 list = g_slist_prepend(list, g_strstrip(column));
323
324 max_columns--;
325 k++;
326 }
327
41d214f6
BV
328 remainder = str + inc->delimiter->len;
329 str = strstr(remainder, inc->delimiter->str);
4a35548b
MS
330 n++;
331 }
332
41d214f6 333 if (buf[0] && max_columns && n >= inc->first_column) {
4a35548b
MS
334 column = g_strdup(remainder);
335 list = g_slist_prepend(list, g_strstrip(column));
336 k++;
337 }
338
339 if (!(columns = g_try_new(char *, k + 1)))
340 return NULL;
341
342 columns[k--] = NULL;
343
344 for (l = list; l; l = l->next)
345 columns[k--] = l->data;
346
347 g_slist_free(list);
348
349 return columns;
350}
351
41d214f6 352static int parse_multi_columns(char **columns, struct context *inc)
4a35548b
MS
353{
354 gsize i;
df0db9fd 355 char *column;
4a35548b
MS
356
357 /* Clear buffer in order to set bits only. */
41d214f6 358 memset(inc->sample_buffer, 0, (inc->num_channels + 7) >> 3);
4a35548b 359
41d214f6 360 for (i = 0; i < inc->num_channels; i++) {
df0db9fd
GS
361 column = columns[i];
362 if (column[0] == '1') {
41d214f6 363 inc->sample_buffer[i / 8] |= (1 << (i % 8));
df0db9fd 364 } else if (!strlen(column)) {
4a35548b 365 sr_err("Column %zu in line %zu is empty.",
41d214f6 366 inc->first_channel + i, inc->line_number);
4a35548b 367 return SR_ERR;
df0db9fd 368 } else if (column[0] != '0') {
4a35548b 369 sr_err("Invalid value '%s' in column %zu in line %zu.",
df0db9fd 370 column, inc->first_channel + i,
41d214f6 371 inc->line_number);
4a35548b
MS
372 return SR_ERR;
373 }
374 }
375
376 return SR_OK;
377}
378
41d214f6 379static int parse_single_column(const char *column, struct context *inc)
4a35548b
MS
380{
381 int res;
382
383 res = SR_ERR;
384
0c5f2abc 385 switch (inc->format) {
4a35548b 386 case FORMAT_BIN:
41d214f6 387 res = parse_binstr(column, inc);
4a35548b
MS
388 break;
389 case FORMAT_HEX:
41d214f6 390 res = parse_hexstr(column, inc);
4a35548b
MS
391 break;
392 case FORMAT_OCT:
41d214f6 393 res = parse_octstr(column, inc);
4a35548b
MS
394 break;
395 }
396
397 return res;
398}
399
400static int send_samples(const struct sr_dev_inst *sdi, uint8_t *buffer,
41d214f6 401 gsize buffer_size, gsize count)
4a35548b 402{
4a35548b
MS
403 struct sr_datafeed_packet packet;
404 struct sr_datafeed_logic logic;
41d214f6 405 int res;
4a35548b
MS
406 gsize i;
407
408 packet.type = SR_DF_LOGIC;
409 packet.payload = &logic;
410 logic.unitsize = buffer_size;
411 logic.length = buffer_size;
412 logic.data = buffer;
413
414 for (i = 0; i < count; i++) {
df0db9fd
GS
415 res = sr_session_send(sdi, &packet);
416 if (res != SR_OK)
4a35548b
MS
417 return res;
418 }
419
420 return SR_OK;
421}
422
41d214f6 423static int init(struct sr_input *in, GHashTable *options)
4a35548b 424{
41d214f6
BV
425 struct context *inc;
426 const char *s;
4a35548b 427
aac29cc1 428 in->sdi = g_malloc0(sizeof(struct sr_dev_inst));
41d214f6 429 in->priv = inc = g_malloc0(sizeof(struct context));
4a35548b 430
41d214f6
BV
431 inc->single_column = g_variant_get_int32(g_hash_table_lookup(options, "single-column"));
432 inc->multi_column_mode = inc->single_column == 0;
4a35548b 433
41d214f6 434 inc->num_channels = g_variant_get_int32(g_hash_table_lookup(options, "numchannels"));
4a35548b 435
41d214f6
BV
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.");
440 return SR_ERR_ARG;
4a35548b
MS
441 }
442
41d214f6
BV
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;
450 } else {
451 sr_err("Invalid format: '%s'", s);
452 return SR_ERR_ARG;
4a35548b
MS
453 }
454
41d214f6
BV
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);
4a35548b
MS
462 }
463
6e8d95a5 464 inc->samplerate = g_variant_get_uint64(g_hash_table_lookup(options, "samplerate"));
4a35548b 465
41d214f6 466 inc->first_channel = g_variant_get_int32(g_hash_table_lookup(options, "first-channel"));
4a35548b 467
41d214f6 468 inc->header = g_variant_get_boolean(g_hash_table_lookup(options, "header"));
4a35548b 469
41d214f6
BV
470 inc->start_line = g_variant_get_int32(g_hash_table_lookup(options, "startline"));
471 if (inc->start_line < 1) {
6433156c 472 sr_err("Invalid start line %zu.", inc->start_line);
41d214f6 473 return SR_ERR_ARG;
4a35548b
MS
474 }
475
41d214f6
BV
476 if (inc->multi_column_mode)
477 inc->first_column = inc->first_channel;
4a35548b 478 else
41d214f6 479 inc->first_column = inc->single_column;
4a35548b 480
41d214f6 481 if (!inc->multi_column_mode && !inc->num_channels) {
ba7dd8bb 482 sr_err("Number of channels needs to be specified in single column mode.");
41d214f6 483 return SR_ERR_ARG;
4a35548b
MS
484 }
485
41d214f6
BV
486 return SR_OK;
487}
4a35548b 488
492dfa90
GS
489static const char *delim_set = "\r\n";
490
329733d9 491static const char *get_line_termination(GString *buf)
41d214f6 492{
329733d9 493 const char *term;
4a35548b 494
41d214f6
BV
495 term = NULL;
496 if (g_strstr_len(buf->str, buf->len, "\r\n"))
497 term = "\r\n";
498 else if (memchr(buf->str, '\n', buf->len))
499 term = "\n";
500 else if (memchr(buf->str, '\r', buf->len))
501 term = "\r";
4a35548b 502
41d214f6
BV
503 return term;
504}
4a35548b 505
41d214f6
BV
506static int initial_parse(const struct sr_input *in, GString *buf)
507{
508 struct context *inc;
41d214f6 509 GString *channel_name;
6433156c
DE
510 unsigned int num_columns, i;
511 size_t line_number, l;
41d214f6 512 int ret;
df0db9fd 513 char **lines, *line, **columns, *column;
41d214f6
BV
514
515 ret = SR_OK;
516 inc = in->priv;
517 columns = NULL;
518
519 line_number = 0;
492dfa90 520 lines = g_strsplit_set(buf->str, delim_set, 0);
41d214f6
BV
521 for (l = 0; lines[l]; l++) {
522 line_number++;
df0db9fd 523 line = lines[l];
41d214f6
BV
524 if (inc->start_line > line_number) {
525 sr_spew("Line %zu skipped.", line_number);
4a35548b
MS
526 continue;
527 }
df0db9fd 528 if (line[0] == '\0') {
41d214f6
BV
529 sr_spew("Blank line %zu skipped.", line_number);
530 continue;
531 }
df0db9fd
GS
532 strip_comment(line, inc->comment);
533 if (line[0] == '\0') {
41d214f6 534 sr_spew("Comment-only line %zu skipped.", line_number);
4a35548b
MS
535 continue;
536 }
537
41d214f6
BV
538 /* Reached first proper line. */
539 break;
540 }
541 if (!lines[l]) {
542 /* Not enough data for a proper line yet. */
60107497 543 ret = SR_ERR_NA;
41d214f6 544 goto out;
4a35548b
MS
545 }
546
547 /*
548 * In order to determine the number of columns parse the current line
549 * without limiting the number of columns.
550 */
df0db9fd
GS
551 columns = parse_line(line, inc, -1);
552 if (!columns) {
41d214f6
BV
553 sr_err("Error while parsing line %zu.", line_number);
554 ret = SR_ERR;
555 goto out;
4a35548b 556 }
4a35548b
MS
557 num_columns = g_strv_length(columns);
558
559 /* Ensure that the first column is not out of bounds. */
560 if (!num_columns) {
6433156c 561 sr_err("Column %u in line %zu is out of bounds.",
41d214f6
BV
562 inc->first_column, line_number);
563 ret = SR_ERR;
564 goto out;
4a35548b
MS
565 }
566
41d214f6 567 if (inc->multi_column_mode) {
4a35548b 568 /*
ba7dd8bb 569 * Detect the number of channels in multi column mode
4a35548b
MS
570 * automatically if not specified.
571 */
41d214f6
BV
572 if (!inc->num_channels) {
573 inc->num_channels = num_columns;
6433156c 574 sr_dbg("Number of auto-detected channels: %u.",
41d214f6 575 inc->num_channels);
4a35548b
MS
576 }
577
578 /*
ba7dd8bb 579 * Ensure that the number of channels does not exceed the number
4a35548b
MS
580 * of columns in multi column mode.
581 */
41d214f6 582 if (num_columns < inc->num_channels) {
ba7dd8bb 583 sr_err("Not enough columns for desired number of channels in line %zu.",
41d214f6
BV
584 line_number);
585 ret = SR_ERR;
586 goto out;
4a35548b
MS
587 }
588 }
589
41d214f6
BV
590 channel_name = g_string_sized_new(64);
591 for (i = 0; i < inc->num_channels; i++) {
df0db9fd
GS
592 column = columns[i];
593 if (inc->header && inc->multi_column_mode && column[0] != '\0')
594 g_string_assign(channel_name, column);
4a35548b 595 else
6433156c 596 g_string_printf(channel_name, "%u", i);
5e23fcab 597 sr_channel_new(in->sdi, i, SR_CHANNEL_LOGIC, TRUE, channel_name->str);
4a35548b 598 }
41d214f6 599 g_string_free(channel_name, TRUE);
4a35548b
MS
600
601 /*
602 * Calculate the minimum buffer size to store the sample data of the
ba7dd8bb 603 * channels.
4a35548b 604 */
41d214f6
BV
605 inc->sample_buffer_size = (inc->num_channels + 7) >> 3;
606 inc->sample_buffer = g_malloc(inc->sample_buffer_size);
4a35548b 607
41d214f6
BV
608out:
609 if (columns)
610 g_strfreev(columns);
611 g_strfreev(lines);
4a35548b 612
41d214f6 613 return ret;
4a35548b
MS
614}
615
4439363a
GS
616/*
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.
625 */
626static void initial_bom_check(const struct sr_input *in)
627{
628 static const char *utf8_bom = "\xef\xbb\xbf";
629
630 if (in->buf->len < strlen(utf8_bom))
631 return;
632 if (strncmp(in->buf->str, utf8_bom, strlen(utf8_bom)) != 0)
633 return;
634 g_string_erase(in->buf, 0, strlen(utf8_bom));
635}
636
41d214f6 637static int initial_receive(const struct sr_input *in)
4a35548b 638{
41d214f6
BV
639 struct context *inc;
640 GString *new_buf;
641 int len, ret;
329733d9
UH
642 char *p;
643 const char *termination;
4a35548b 644
4439363a
GS
645 initial_bom_check(in);
646
41d214f6 647 inc = in->priv;
4a35548b 648
df0db9fd
GS
649 termination = get_line_termination(in->buf);
650 if (!termination)
41d214f6 651 /* Don't have a full line yet. */
d0181813 652 return SR_ERR_NA;
4a35548b 653
df0db9fd
GS
654 p = g_strrstr_len(in->buf->str, in->buf->len, termination);
655 if (!p)
41d214f6 656 /* Don't have a full line yet. */
d0181813 657 return SR_ERR_NA;
41d214f6
BV
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');
4a35548b 661
41d214f6
BV
662 inc->termination = g_strdup(termination);
663
664 if (in->buf->str[0] != '\0')
665 ret = initial_parse(in, new_buf);
666 else
667 ret = SR_OK;
668
669 g_string_free(new_buf, TRUE);
670
671 return ret;
672}
673
7f4c3a62 674static int process_buffer(struct sr_input *in, gboolean is_eof)
41d214f6
BV
675{
676 struct sr_datafeed_packet packet;
677 struct sr_datafeed_meta meta;
678 struct sr_config *src;
679 struct context *inc;
680 gsize num_columns;
681 uint64_t samplerate;
682 int max_columns, ret, l;
df0db9fd 683 char *p, **lines, *line, **columns;
41d214f6 684
41d214f6 685 inc = in->priv;
d0181813 686 if (!inc->started) {
bee2b016 687 std_session_send_df_header(in->sdi);
41d214f6
BV
688
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);
c01378c9 696 g_slist_free(meta.config);
41d214f6
BV
697 sr_config_free(src);
698 }
d0181813
BV
699
700 inc->started = TRUE;
4a35548b
MS
701 }
702
f9b74861
GS
703 /* Limit the number of columns to parse. */
704 if (inc->multi_column_mode)
705 max_columns = inc->num_channels;
706 else
707 max_columns = 1;
708
4555d3bd
GS
709 /*
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.
7f4c3a62
GS
715 *
716 * Enforce that all previously buffered data gets processed in
717 * the "EOF" condition. Do not insist in the presence of the
718 * termination sequence for the last line (may often be missing
719 * on Windows). A present termination sequence will just result
720 * in the "execution of an empty line", and does not harm.
4555d3bd
GS
721 */
722 if (!in->buf->len)
723 return SR_OK;
7f4c3a62
GS
724 if (is_eof) {
725 p = in->buf->str + in->buf->len;
726 } else {
727 p = g_strrstr_len(in->buf->str, in->buf->len, inc->termination);
728 if (!p)
729 return SR_ERR;
730 *p = '\0';
731 p += strlen(inc->termination);
732 }
41d214f6 733 g_strstrip(in->buf->str);
4a35548b 734
18078d05 735 ret = SR_OK;
492dfa90 736 lines = g_strsplit_set(in->buf->str, delim_set, 0);
41d214f6
BV
737 for (l = 0; lines[l]; l++) {
738 inc->line_number++;
df0db9fd
GS
739 line = lines[l];
740 if (line[0] == '\0') {
41d214f6 741 sr_spew("Blank line %zu skipped.", inc->line_number);
4a35548b
MS
742 continue;
743 }
744
745 /* Remove trailing comment. */
df0db9fd
GS
746 strip_comment(line, inc->comment);
747 if (line[0] == '\0') {
41d214f6 748 sr_spew("Comment-only line %zu skipped.", inc->line_number);
4a35548b
MS
749 continue;
750 }
751
160691b9
JS
752 /* Skip the header line, its content was used as the channel names. */
753 if (inc->header) {
754 sr_spew("Header line %zu skipped.", inc->line_number);
755 inc->header = FALSE;
756 continue;
757 }
758
df0db9fd
GS
759 columns = parse_line(line, inc, max_columns);
760 if (!columns) {
41d214f6 761 sr_err("Error while parsing line %zu.", inc->line_number);
4a35548b
MS
762 return SR_ERR;
763 }
4a35548b 764 num_columns = g_strv_length(columns);
4a35548b 765 if (!num_columns) {
6433156c 766 sr_err("Column %u in line %zu is out of bounds.",
41d214f6 767 inc->first_column, inc->line_number);
4a35548b 768 g_strfreev(columns);
4a35548b
MS
769 return SR_ERR;
770 }
4a35548b 771 /*
ba7dd8bb 772 * Ensure that the number of channels does not exceed the number
4a35548b
MS
773 * of columns in multi column mode.
774 */
41d214f6 775 if (inc->multi_column_mode && num_columns < inc->num_channels) {
ba7dd8bb 776 sr_err("Not enough columns for desired number of channels in line %zu.",
41d214f6 777 inc->line_number);
4a35548b 778 g_strfreev(columns);
4a35548b
MS
779 return SR_ERR;
780 }
781
41d214f6
BV
782 if (inc->multi_column_mode)
783 ret = parse_multi_columns(columns, inc);
4a35548b 784 else
41d214f6
BV
785 ret = parse_single_column(columns[0], inc);
786 if (ret != SR_OK) {
4a35548b 787 g_strfreev(columns);
4a35548b
MS
788 return SR_ERR;
789 }
790
4a35548b 791 /* Send sample data to the session bus. */
41d214f6
BV
792 ret = send_samples(in->sdi, inc->sample_buffer,
793 inc->sample_buffer_size, 1);
794 if (ret != SR_OK) {
4a35548b 795 sr_err("Sending samples failed.");
4a35548b
MS
796 return SR_ERR;
797 }
41d214f6
BV
798 g_strfreev(columns);
799 }
800 g_strfreev(lines);
241c386a 801 g_string_erase(in->buf, 0, p - in->buf->str);
41d214f6 802
7066fd46 803 return ret;
41d214f6
BV
804}
805
7066fd46 806static int receive(struct sr_input *in, GString *buf)
41d214f6
BV
807{
808 struct context *inc;
7066fd46
BV
809 int ret;
810
811 g_string_append_len(in->buf, buf->str, buf->len);
41d214f6
BV
812
813 inc = in->priv;
7066fd46 814 if (!inc->termination) {
df0db9fd
GS
815 ret = initial_receive(in);
816 if (ret == SR_ERR_NA)
7066fd46
BV
817 /* Not enough data yet. */
818 return SR_OK;
819 else if (ret != SR_OK)
820 return SR_ERR;
821
822 /* sdi is ready, notify frontend. */
823 in->sdi_ready = TRUE;
41d214f6 824 return SR_OK;
7066fd46
BV
825 }
826
7f4c3a62 827 ret = process_buffer(in, FALSE);
7066fd46
BV
828
829 return ret;
830}
831
832static int end(struct sr_input *in)
833{
834 struct context *inc;
7066fd46 835 int ret;
41d214f6 836
7066fd46 837 if (in->sdi_ready)
7f4c3a62 838 ret = process_buffer(in, TRUE);
7066fd46
BV
839 else
840 ret = SR_OK;
841
842 inc = in->priv;
3be42bc2 843 if (inc->started)
bee2b016 844 std_session_send_df_end(in->sdi);
4a35548b 845
7066fd46
BV
846 return ret;
847}
848
d5cc282f 849static void cleanup(struct sr_input *in)
7066fd46
BV
850{
851 struct context *inc;
852
853 inc = in->priv;
854
41d214f6
BV
855 if (inc->delimiter)
856 g_string_free(inc->delimiter, TRUE);
857
858 if (inc->comment)
859 g_string_free(inc->comment, TRUE);
4a35548b 860
b1f83103
UH
861 g_free(inc->termination);
862 g_free(inc->sample_buffer);
4a35548b
MS
863}
864
ad93bfb0
SA
865static int reset(struct sr_input *in)
866{
867 struct context *inc = in->priv;
868
869 cleanup(in);
870 inc->started = FALSE;
871 g_string_truncate(in->buf, 0);
872
873 return SR_OK;
874}
875
41d214f6
BV
876static struct sr_option options[] = {
877 { "single-column", "Single column", "Enable/specify single column", NULL, NULL },
878 { "numchannels", "Max channels", "Number of channels", NULL, NULL },
879 { "delimiter", "Delimiter", "Column delimiter", NULL, NULL },
880 { "format", "Format", "Numeric format", NULL, NULL },
881 { "comment", "Comment", "Comment prefix character", NULL, NULL },
882 { "samplerate", "Samplerate", "Samplerate used during capture", NULL, NULL },
883 { "first-channel", "First channel", "Column number of first channel", NULL, NULL },
884 { "header", "Header", "Treat first line as header with channel names", NULL, NULL },
885 { "startline", "Start line", "Line number at which to start processing samples", NULL, NULL },
06ad20be 886 ALL_ZERO
41d214f6
BV
887};
888
2c240774 889static const struct sr_option *get_options(void)
41d214f6
BV
890{
891 if (!options[0].def) {
892 options[0].def = g_variant_ref_sink(g_variant_new_int32(0));
893 options[1].def = g_variant_ref_sink(g_variant_new_int32(0));
894 options[2].def = g_variant_ref_sink(g_variant_new_string(","));
895 options[3].def = g_variant_ref_sink(g_variant_new_string("bin"));
896 options[4].def = g_variant_ref_sink(g_variant_new_string(";"));
6e8d95a5 897 options[5].def = g_variant_ref_sink(g_variant_new_uint64(0));
41d214f6
BV
898 options[6].def = g_variant_ref_sink(g_variant_new_int32(0));
899 options[7].def = g_variant_ref_sink(g_variant_new_boolean(FALSE));
900 options[8].def = g_variant_ref_sink(g_variant_new_int32(1));
901 }
902
903 return options;
904}
905
d4c93774 906SR_PRIV struct sr_input_module input_csv = {
4a35548b 907 .id = "csv",
41d214f6
BV
908 .name = "CSV",
909 .desc = "Comma-separated values",
c7bc82ff 910 .exts = (const char*[]){"csv", NULL},
41d214f6 911 .options = get_options,
4a35548b 912 .init = init,
41d214f6 913 .receive = receive,
7066fd46 914 .end = end,
41d214f6 915 .cleanup = cleanup,
ad93bfb0 916 .reset = reset,
4a35548b 917};