]> git.itanic.dy.fi Git - log-plotter/blob - data.c
data.c: Implement initial support for handling multiple data channels
[log-plotter] / data.c
1 #include <unistd.h>
2 #include <stdio.h>
3 #include <string.h>
4 #include <time.h>
5 #include <stdlib.h>
6 #include <unistd.h>
7 #include <fcntl.h>
8 #include <sys/epoll.h>
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 #include <string.h>
12 #include <math.h>
13
14 #include "data.h"
15 #include "trace.h"
16 #include "event.h"
17 #include "utils.h"
18 #include "event.h"
19 #include "plotter_status.h"
20
21 #define MAX_CHANNELS 4
22
23 struct dataparser_struct {
24         struct eventhandler_entry evhandler;
25         struct plotter_config *cfg;
26         int infd;
27         int outfd[MAX_CHANNELS];
28         int offset;
29         time_t start_time;
30         char buf[256];
31 };
32
33 static int separate_entries(char *buf, char *entries[], int max_entries)
34 {
35         int i = 0;
36
37         entries[i] = buf;
38         i++;
39
40         while (*buf && i< max_entries) {
41                 if (*buf != ';') {
42                         buf++;
43                         continue;
44                 }
45
46                 *buf = 0;
47                 buf++;
48                 entries[i] = buf;
49                 i++;
50         }
51
52         return i;
53 }
54
55 static void init_data(struct charger_data *data)
56 {
57         int i;
58
59         bzero(data, sizeof(*data));
60         for (i = 0; i < MAX_CELLS; i++)
61                 data->cell_voltage[i] = NAN;
62
63         data->timestamp = NAN;
64         data->input_voltage = NAN;
65         data->charging_voltage = NAN;
66         data->charging_current = NAN;
67         data->total_charge = NAN;
68         data->int_temp = NAN;
69         data->ext_temp = NAN;
70 }
71
72 /*
73  * Convert one log line into charger_data structure. Supports at least
74  * iCharger 6 and 10 cell chargers. Others are not tested.
75  *
76  * Returns negative on incorrect data, zero on success
77  */
78 static int parse_logline(const char *buf, struct charger_data *data)
79 {
80         int i, j, entry_count;
81         int ret = -1;
82         int max_cells;
83         int d;
84         char *str = strdup(buf);
85         char *entries[64];
86
87         entry_count = separate_entries(str, entries, ARRAY_SIZE(entries));
88
89         init_data(data);
90
91         if (entries[0][0] != '$') {
92                 pr_debug("Discarding malformed data entry\n");
93                 goto out;
94         }
95
96         i = 0;
97         entries[i]++; /* discard the dollar sign */
98         data->channel = atoi(entries[i++]);
99         if (data->channel > MAX_CHANNELS)
100                 data->channel = 0;
101
102         data->state = atoi(entries[i++]);
103
104         /* Timestamp is optional */
105         if (strlen(entries[1]) > 0)
106                 data->timestamp = atof(entries[i++]);
107
108         data->input_voltage = atof(entries[i++]) / 1000.0;
109         data->charging_voltage = atof(entries[i++]) / 1000.0;
110         data->charging_current = atof(entries[i++]) / 100.0;
111
112 #define ASSIGN_OR_NAN(data, val)                \
113         do {                                    \
114                 if ((val) == 0)                 \
115                         (data) = NAN;           \
116                 else                            \
117                         (data) = val;           \
118         } while(0);
119
120         max_cells = entry_count - 10;
121         pr_debug("max_cells: %d\n", max_cells);
122
123         for (j = 0; j < max_cells; j++, i++) {
124                 d = atoi(entries[i]);
125                 ASSIGN_OR_NAN(data->cell_voltage[j], d / 1000.0);
126         }
127
128         d = atoi(entries[i++]);
129         ASSIGN_OR_NAN(data->int_temp, d / 10.0);
130
131         d = atoi(entries[i++]);
132         ASSIGN_OR_NAN(data->ext_temp, d / 10.0);
133
134         data->total_charge = atof(entries[i++]);
135
136         ret = 0;
137 out:
138         free(str);
139         return ret;
140 }
141
142 static void dump_data(struct charger_data *data)
143 {
144         int i;
145
146         pr_debug("channel %d\n", data->channel);
147         pr_debug("state %d\n", data->state);
148         pr_debug("timestamp %.1f\n", data->timestamp);
149         pr_debug("input_voltage %.3f\n", data->input_voltage);
150         pr_debug("charging_voltage %.3f\n", data->charging_voltage);
151         pr_debug("charging_current %.3f\n", data->charging_current);
152
153         for (i = 0; i < MAX_CELLS; i++) {
154                 if (isnan(data->cell_voltage[i]))
155                         continue;
156
157                 pr_debug("cell_voltage[%d] %f\n", i,
158                         data->cell_voltage[i]);
159         }
160
161         pr_debug("total_charge %.0f\n", data->total_charge);
162         pr_debug("int_temp %.1f\n", data->int_temp);
163         pr_debug("ext_temp %.1f\n", data->ext_temp);
164 }
165
166 static void print_status_line(struct charger_data *data)
167 {
168         int i, active_cells = 0;
169         double cell_avg = 0;
170         char time_str[16];
171
172         if (data->timestamp > 3600) {
173                 snprintf(time_str, sizeof(time_str), "%d:%02d:%02d",
174                         (int)(data->timestamp / 3600),
175                         (int)((int)data->timestamp % 3600) / 60,
176                         (int)data->timestamp % 60);
177         } else {
178                 snprintf(time_str, sizeof(time_str), "%2d:%02d",
179                         ((int)data->timestamp % 3600) / 60,
180                         (int)data->timestamp % 60);
181         }
182
183         for (i = 0; i < MAX_CELLS; i++) {
184                 if (!isnan(data->cell_voltage[i])) {
185                         cell_avg += data->cell_voltage[i];
186                         active_cells++;
187                 }
188         }
189         cell_avg /= (double)active_cells;
190
191         pr_info("\r\033[K%s [%s] Ubat: %.3fV Ucell avg: %.3fV "
192                 "Current: %.2fA Charge %.0fmAh ",
193                 time_str,
194                 state_to_str(data->state),
195                 data->charging_voltage, cell_avg,
196                 data->charging_current, data->total_charge);
197
198         fflush(stdout);
199
200 }
201
202 /**
203  * Read data from a slow device
204  *
205  * return 1 when a complete NULL terminated line has been read
206  *
207  * return 0 when a partial line has been read and appended to the
208  *               buffer at @offset
209  *
210  * return negative on error
211  */
212 static int read_log_line(int infd, char *buf, size_t bufsize, int *offset)
213 {
214         int ret;
215         int i;
216
217         ret = read(infd, buf + *offset, bufsize - *offset - 1);
218         if (ret < 0) {
219                 pr_err("read: %m\n");
220                 return -1;
221         }
222
223         if (ret == 0) {
224                 pr_err("Read EOF, stopping\n");
225
226                 set_plotter_system_status(SYSTEM_STATUS_NO_USB);
227                 return -1;
228         }
229         buf[*offset + ret] = 0;
230
231         for (i = 0; i < ret; i++) {
232                 if (buf[i + *offset] == '\n' ||
233                     buf[i + *offset] == '\r') {
234                         /*
235                          * Got a complete line when there is a newline
236                          * at the end. Remove the newline and possible
237                          * other junk, such as '\r'
238                          */
239                         buf[i + *offset] = 0;
240                         *offset = 0;
241
242                         return 1;
243                 }
244
245                 /*
246                  * Fixme! Nothing guarantees that there isn't actually
247                  * more data (a part of a new log entry perhaps) after
248                  * the newline. So in rare cases (we are prevented
249                  * from reading the serial line in very long time) we
250                  * might lose data from the stream..
251                  */
252         }
253
254         *offset += ret;
255         return 0;
256 }
257
258 static int open_new_logfile(struct dataparser_struct *dt, int channel)
259 {
260         char path[2048];
261         struct tm *tm;
262         time_t cur_time = time(NULL);
263
264         tm = localtime(&cur_time);
265         strftime(path, sizeof(path), dt->cfg->log_path, tm);
266
267         store_int_variable_value_to_array("channel", channel, dt->cfg);
268         replace_variables_with_values(path, sizeof(path), dt->cfg);
269
270         pr_debug("Opening %s for writing the log file\n", path);
271
272         dt->outfd[channel] = open(path, O_CREAT | O_APPEND | O_WRONLY, 0664);
273         if (dt->outfd[channel] < 0) {
274                 pr_err("Failed to open file %s for writing: %m\n",
275                         path);
276                 return -1;
277         }
278
279         return 0;
280 }
281
282 static int read_data(struct eventhandler_entry *h)
283 {
284         struct dataparser_struct *dt;
285         time_t cur_time;
286         int ret;
287         struct charger_data data;
288         char str[320];
289         int len;
290
291         dt = container_of(h, struct dataparser_struct, evhandler);
292
293         ret = read_log_line(dt->infd, dt->buf, sizeof(dt->buf), &dt->offset);
294         if (ret <= 0)
295                 return ret;
296
297         if (ret == 0)
298                 pr_err("%s %s: EOF\n", __FILE__, __func__);
299
300         if (strlen(dt->buf) < 5) {
301                 pr_debug("discarding truncated log entry\n");
302                 dt->offset = 0;
303                 return 0;
304         }
305
306         if (!dt->start_time)
307                 dt->start_time = time(NULL);
308
309         cur_time = time(NULL);
310
311         parse_logline(dt->buf, &data);
312
313         set_plotter_system_status(data.state);
314
315         /* Fill in possibly missing timestamp */
316         if (isnan(data.timestamp) || data.timestamp == 0)
317                 data.timestamp = cur_time - dt->start_time;
318
319         print_status_line(&data);
320
321         if (0)
322                 dump_data(&data);
323
324         if (!dt->cfg->log_path)
325                 return 0;
326
327         if (state_has_changed()) {
328                 ret = open_new_logfile(dt, data.channel);
329                 if (ret < 0)
330                         return ret;
331         }
332
333         len = snprintf(str, sizeof(str),
334                 "%d;%d;%.1f;"
335                 "%.3f;%.3f;%.3f;"
336                 "%.3f;%.3f;%.3f;%.3f;%.3f;%.3f;%.3f;%.3f;%.3f;%.3f;"
337                 "%.f;%.1f;%.1f\n", /* mAh, and temp */
338                 data.channel,
339                 data.state,
340                 data.timestamp,
341
342                 data.input_voltage,
343                 data.charging_voltage,
344                 data.charging_current,
345
346                 data.cell_voltage[0],
347                 data.cell_voltage[1],
348                 data.cell_voltage[2],
349                 data.cell_voltage[3],
350                 data.cell_voltage[4],
351                 data.cell_voltage[5],
352                 data.cell_voltage[6],
353                 data.cell_voltage[7],
354                 data.cell_voltage[8],
355                 data.cell_voltage[9],
356                 data.int_temp,
357                 data.ext_temp,
358                 data.total_charge);
359
360         if (dt->outfd[data.channel] <= 0)
361                 open_new_logfile(dt, data.channel);
362
363         ret = write(dt->outfd[data.channel], str, len);
364         if (ret < 0) {
365                 pr_err("write: %m\n");
366                 return -1;;
367         }
368
369         return 0;
370 }
371
372 static struct dataparser_struct dataparser = {
373         .evhandler.name = "OpenLog Parser",
374         .evhandler.events = EPOLLIN,
375         .evhandler.handle_event = read_data,
376 };
377
378 int init_data_parser(int infd, struct plotter_config *cfg)
379 {
380         int ret;
381
382         dataparser.evhandler.fd = infd;
383         dataparser.infd = infd;
384         dataparser.cfg = cfg;
385
386         ret = register_event_handler(&dataparser.evhandler);
387         if (ret < 0)
388                 return 1;
389
390         return 0;
391 }