]> sigrok.org Git - libsigrok.git/blob - src/hardware/baylibre-acme/protocol.c
Revert "baylibre-acme: Fix a compiler warning."
[libsigrok.git] / src / hardware / baylibre-acme / protocol.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2015 Bartosz Golaszewski <bgolaszewski@baylibre.com>
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
20 #include <string.h>
21 #include <stdlib.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <glib/gstdio.h>
25 #include "protocol.h"
26 #include "gpio.h"
27
28 struct channel_group_priv {
29         int hwmon_num;
30         int probe_type;
31         int index;
32 };
33
34 struct channel_priv {
35         int ch_type;
36         struct channel_group_priv *probe;
37 };
38
39 static const uint8_t enrg_i2c_addrs[] = {
40         0x40, 0x41, 0x44, 0x45, 0x42, 0x43, 0x46, 0x47,
41 };
42
43 static const uint8_t temp_i2c_addrs[] = {
44         0x0, 0x0, 0x0, 0x0, 0x4c, 0x49, 0x4f, 0x4b,
45 };
46
47 static const uint32_t pws_gpios[] = {
48         486, 498, 502, 482, 478, 506, 510, 474,
49 };
50
51 static const uint32_t pws_info_gpios[] = {
52         487, 499, 503, 483, 479, 507, 511, 475,
53 };
54
55 #define MOHM_TO_UOHM(x) ((x) * 1000)
56 #define UOHM_TO_MOHM(x) ((x) / 1000)
57
58 SR_PRIV uint8_t bl_acme_get_enrg_addr(int index)
59 {
60         return enrg_i2c_addrs[index];
61 }
62
63 SR_PRIV uint8_t bl_acme_get_temp_addr(int index)
64 {
65         return temp_i2c_addrs[index];
66 }
67
68 SR_PRIV gboolean bl_acme_is_sane(void)
69 {
70         gboolean status;
71
72         /*
73          * We expect sysfs to be present and mounted at /sys, ina226 and
74          * tmp435 sensors detected by the system and their appropriate
75          * drivers loaded and functional.
76          */
77         status = g_file_test("/sys", G_FILE_TEST_IS_DIR);
78         if (!status) {
79                 sr_err("/sys/ directory not found - sysfs not mounted?");
80                 return FALSE;
81         }
82
83         return TRUE;
84 }
85
86 static void probe_name_path(unsigned int addr, GString *path)
87 {
88         g_string_printf(path,
89                         "/sys/class/i2c-adapter/i2c-1/1-00%02x/name", addr);
90 }
91
92 /*
93  * For given address fill buf with the path to appropriate hwmon entry.
94  */
95 static void probe_hwmon_path(unsigned int addr, GString *path)
96 {
97         g_string_printf(path,
98                         "/sys/class/i2c-adapter/i2c-1/1-00%02x/hwmon", addr);
99 }
100
101 SR_PRIV gboolean bl_acme_detect_probe(unsigned int addr,
102                                       int prb_num, const char *prb_name)
103 {
104         gboolean ret = FALSE, status;
105         char *buf = NULL;
106         GString *path = g_string_sized_new(64);
107         GError *err = NULL;
108         gsize size;
109
110         probe_name_path(addr, path);
111         status = g_file_get_contents(path->str, &buf, &size, &err);
112         if (!status) {
113                 sr_dbg("Name for probe %d can't be read: %s",
114                        prb_num, err->message);
115                 g_string_free(path, TRUE);
116                 return ret;
117         }
118
119         if (!strncmp(buf, prb_name, strlen(prb_name))) {
120                 /*
121                  * Correct driver registered on this address - but is
122                  * there an actual probe connected?
123                  */
124                 probe_hwmon_path(addr, path);
125                 status = g_file_test(path->str, G_FILE_TEST_IS_DIR);
126                 if (status) {
127                         /* We have found an ACME probe. */
128                         ret = TRUE;
129                 }
130         }
131
132         g_free(buf);
133         g_string_free(path, TRUE);
134
135         return ret;
136 }
137
138 static int get_hwmon_index(unsigned int addr)
139 {
140         int status, hwmon;
141         GString *path = g_string_sized_new(64);
142         GError *err = NULL;
143         GDir *dir;
144
145         probe_hwmon_path(addr, path);
146         dir = g_dir_open(path->str, 0, &err);
147         if (!dir) {
148                 sr_err("Error opening %s: %s", path->str, err->message);
149                 g_string_free(path, TRUE);
150                 return -1;
151         }
152
153         g_string_free(path, TRUE);
154
155         /*
156          * The directory should contain a single file named hwmonX where X
157          * is the hwmon index.
158          */
159         status = sscanf(g_dir_read_name(dir), "hwmon%d", &hwmon);
160         g_dir_close(dir);
161         if (status != 1) {
162                 sr_err("Unable to determine the hwmon entry");
163                 return -1;
164         }
165
166         return hwmon;
167 }
168
169 static void append_channel(struct sr_dev_inst *sdi, struct sr_channel_group *cg,
170                            int index, int type)
171 {
172         struct channel_priv *cp;
173         struct dev_context *devc;
174         struct sr_channel *ch;
175         char *name;
176
177         devc = sdi->priv;
178
179         switch (type) {
180         case ENRG_PWR:
181                 name = g_strdup_printf("P%d_ENRG_PWR", index);
182                 break;
183         case ENRG_CURR:
184                 name = g_strdup_printf("P%d_ENRG_CURR", index);
185                 break;
186         case ENRG_VOL:
187                 name = g_strdup_printf("P%d_ENRG_VOL", index);
188                 break;
189         case TEMP_IN:
190                 name = g_strdup_printf("P%d_TEMP_IN", index);
191                 break;
192         case TEMP_OUT:
193                 name = g_strdup_printf("P%d_TEMP_OUT", index);
194                 break;
195         default:
196                 sr_err("Invalid channel type: %d.", type);
197                 return;
198         }
199
200         cp = g_malloc0(sizeof(struct channel_priv));
201         cp->ch_type = type;
202         cp->probe = cg->priv;
203
204         ch = sr_channel_new(sdi, devc->num_channels++,
205                             SR_CHANNEL_ANALOG, TRUE, name);
206         g_free(name);
207
208         ch->priv = cp;
209         cg->channels = g_slist_append(cg->channels, ch);
210 }
211
212 SR_PRIV gboolean bl_acme_register_probe(struct sr_dev_inst *sdi, int type,
213                                         unsigned int addr, int prb_num)
214 {
215         struct sr_channel_group *cg;
216         struct channel_group_priv *cgp;
217         int hwmon;
218
219         /* Obtain the hwmon index. */
220         hwmon = get_hwmon_index(addr);
221         if (hwmon < 0)
222                 return FALSE;
223
224         cg = g_malloc0(sizeof(struct sr_channel_group));
225         cgp = g_malloc0(sizeof(struct channel_group_priv));
226         cgp->hwmon_num = hwmon;
227         cgp->probe_type = type;
228         cgp->index = prb_num - 1;
229         cg->name = g_strdup_printf("Probe_%d", prb_num);
230         cg->priv = cgp;
231
232         if (type == PROBE_ENRG) {
233                 append_channel(sdi, cg, prb_num, ENRG_PWR);
234                 append_channel(sdi, cg, prb_num, ENRG_CURR);
235                 append_channel(sdi, cg, prb_num, ENRG_VOL);
236         } else if (type == PROBE_TEMP) {
237                 append_channel(sdi, cg, prb_num, TEMP_IN);
238                 append_channel(sdi, cg, prb_num, TEMP_OUT);
239         } else {
240                 sr_err("Invalid probe type: %d.", type);
241         }
242
243         sdi->channel_groups = g_slist_append(sdi->channel_groups, cg);
244
245         return TRUE;
246 }
247
248 SR_PRIV int bl_acme_get_probe_type(const struct sr_channel_group *cg)
249 {
250         struct channel_group_priv *cgp = cg->priv;
251
252         return cgp->probe_type;
253 }
254
255 SR_PRIV int bl_acme_probe_has_pws(const struct sr_channel_group *cg)
256 {
257         struct channel_group_priv *cgp = cg->priv;
258
259         return sr_gpio_getval_export(pws_info_gpios[cgp->index]);
260 }
261
262 /*
263  * Sets path to the hwmon attribute if this channel group
264  * supports shunt resistance setting. The caller has to supply
265  * a valid GString.
266  */
267 static int get_shunt_path(const struct sr_channel_group *cg, GString *path)
268 {
269         struct channel_group_priv *cgp;
270         int ret = SR_OK, status;
271
272         cgp = cg->priv;
273
274         if (cgp->probe_type != PROBE_ENRG) {
275                 sr_err("Probe doesn't support shunt resistance setting");
276                 return SR_ERR_ARG;
277         }
278
279         g_string_append_printf(path,
280                                "/sys/class/hwmon/hwmon%d/shunt_resistor",
281                                cgp->hwmon_num);
282
283         /*
284          * The shunt_resistor sysfs attribute is available
285          * in the Linux kernel since version 3.20. We have
286          * to notify the user if this attribute is not present.
287          */
288         status = g_file_test(path->str, G_FILE_TEST_EXISTS);
289         if (!status) {
290                 sr_err("shunt_resistance attribute not present, please update "
291                        "your kernel to version >=3.20");
292                 return SR_ERR_NA;
293         }
294
295         return ret;
296 }
297
298 /*
299  * Try setting the update_interval sysfs attribute for each probe according
300  * to samplerate.
301  */
302 SR_PRIV void bl_acme_maybe_set_update_interval(const struct sr_dev_inst *sdi,
303                                                uint64_t samplerate)
304 {
305         struct sr_channel_group *cg;
306         struct channel_group_priv *cgp;
307         GString *hwmon;
308         GSList *l;
309         FILE *fd;
310
311         for (l = sdi->channel_groups; l != NULL; l = l->next) {
312                 cg = l->data;
313                 cgp = cg->priv;
314
315                 hwmon = g_string_sized_new(64);
316                 g_string_append_printf(hwmon,
317                                 "/sys/class/hwmon/hwmon%d/update_interval",
318                                 cgp->hwmon_num);
319
320                 if (g_file_test(hwmon->str, G_FILE_TEST_EXISTS)) {
321                         fd = g_fopen(hwmon->str, "w");
322                         if (!fd) {
323                                 g_string_free(hwmon, TRUE);
324                                 continue;
325                         }
326
327                         g_fprintf(fd, "%" PRIu64 "\n", 1000 / samplerate);
328                         fclose(fd);
329                 }
330
331                 g_string_free(hwmon, TRUE);
332         }
333 }
334
335 SR_PRIV int bl_acme_get_shunt(const struct sr_channel_group *cg,
336                               uint64_t *shunt)
337 {
338         GString *path = g_string_sized_new(64);
339         gchar *contents;
340         int status, ret = SR_OK;
341         GError *err = NULL;
342
343         status = get_shunt_path(cg, path);
344         if (status != SR_OK) {
345                 ret = status;
346                 goto out;
347         }
348
349         status = g_file_get_contents(path->str, &contents, NULL, &err);
350         if (!status) {
351                 sr_err("Error reading shunt resistance: %s", err->message);
352                 ret = SR_ERR_IO;
353                 goto out;
354         }
355
356         *shunt = UOHM_TO_MOHM(strtol(contents, NULL, 10));
357
358 out:
359         g_string_free(path, TRUE);
360         return ret;
361 }
362
363 SR_PRIV int bl_acme_set_shunt(const struct sr_channel_group *cg, uint64_t shunt)
364 {
365         GString *path = g_string_sized_new(64);;
366         int status, ret = SR_OK;
367         FILE *fd;
368
369         status = get_shunt_path(cg, path);
370         if (status != SR_OK) {
371                 ret = status;
372                 goto out;
373         }
374
375         /*
376          * Can't use g_file_set_contents() here, as it calls open() with
377          * O_EXEC flag in a sysfs directory thus failing with EACCES.
378          */
379         fd = g_fopen(path->str, "w");
380         if (!fd) {
381                 sr_err("Error opening %s: %s", path->str, strerror(errno));
382                 ret = SR_ERR_IO;
383                 goto out;
384         }
385
386         g_fprintf(fd, "%" PRIu64 "\n", MOHM_TO_UOHM(shunt));
387         fclose(fd);
388
389 out:
390         g_string_free(path, TRUE);
391         return ret;
392 }
393
394 SR_PRIV int bl_acme_read_power_state(const struct sr_channel_group *cg,
395                                      gboolean *off)
396 {
397         struct channel_group_priv *cgp;
398         int val;
399
400         cgp = cg->priv;
401
402         if (!bl_acme_probe_has_pws(cg)) {
403                 sr_err("Probe has no power-switch");
404                 return SR_ERR_ARG;
405         }
406
407         val = sr_gpio_getval_export(pws_gpios[cgp->index]);
408         *off = val ? FALSE : TRUE;
409
410         return SR_OK;
411 }
412
413 SR_PRIV int bl_acme_set_power_off(const struct sr_channel_group *cg,
414                                   gboolean off)
415 {
416         struct channel_group_priv *cgp;
417         int val;
418
419         cgp = cg->priv;
420
421         if (!bl_acme_probe_has_pws(cg)) {
422                 sr_err("Probe has no power-switch");
423                 return SR_ERR_ARG;
424         }
425
426         val = sr_gpio_setval_export(pws_gpios[cgp->index], off ? 0 : 1);
427
428         return SR_OK;
429 }
430
431 static int channel_to_mq(struct sr_channel *ch)
432 {
433         struct channel_priv *chp;
434
435         chp = ch->priv;
436
437         switch (chp->ch_type) {
438         case ENRG_PWR:
439                 return SR_MQ_POWER;
440         case ENRG_CURR:
441                 return SR_MQ_CURRENT;
442         case ENRG_VOL:
443                 return SR_MQ_VOLTAGE;
444         case TEMP_IN: /* Fallthrough */
445         case TEMP_OUT:
446                 return SR_MQ_TEMPERATURE;
447         default:
448                 return -1;
449         }
450 }
451
452 static int channel_to_unit(struct sr_channel *ch)
453 {
454         struct channel_priv *chp;
455
456         chp = ch->priv;
457
458         switch (chp->ch_type) {
459         case ENRG_PWR:
460                 return SR_UNIT_WATT;
461         case ENRG_CURR:
462                 return SR_UNIT_AMPERE;
463         case ENRG_VOL:
464                 return SR_UNIT_VOLT;
465         case TEMP_IN: /* Fallthrough */
466         case TEMP_OUT:
467                 return SR_UNIT_CELSIUS;
468         default:
469                 return -1;
470         }
471 }
472
473 /* We need to scale measurements down from the units used by the drivers. */
474 static float adjust_data(int val, int type)
475 {
476         switch (type) {
477         case ENRG_PWR:
478                 return ((float)val) / 1000000.0;
479         case ENRG_CURR: /* Fallthrough */
480         case ENRG_VOL: /* Fallthrough */
481         case TEMP_IN: /* Fallthrough */
482         case TEMP_OUT:
483                 return ((float)val) / 1000.0;
484         default:
485                 return 0.0;
486         }
487 }
488
489 static float read_sample(struct sr_channel *ch)
490 {
491         struct channel_priv *chp;
492         char path[64], *file, buf[16];
493         ssize_t len;
494         int fd;
495
496         chp = ch->priv;
497
498         switch (chp->ch_type) {
499         case ENRG_PWR:  file = "power1_input";  break;
500         case ENRG_CURR: file = "curr1_input";   break;
501         case ENRG_VOL:  file = "in1_input";     break;
502         case TEMP_IN:   file = "temp1_input";   break;
503         case TEMP_OUT:  file = "temp2_input";   break;
504         default:
505                 sr_err("Invalid channel type: %d.", chp->ch_type);
506                 return -1.0;
507         }
508
509         snprintf(path, sizeof(path), "/sys/class/hwmon/hwmon%d/%s",
510                  chp->probe->hwmon_num, file);
511         fd = open(path, O_RDONLY);
512         if (fd < 0) {
513                 sr_err("Error opening %s: %s", path, strerror(errno));
514                 ch->enabled = FALSE;
515                 return -1.0;
516         }
517
518         len = read(fd, buf, sizeof(buf));
519         close(fd);
520         if (len < 0) {
521                 sr_err("Error reading from %s: %s", path, strerror(errno));
522                 ch->enabled = FALSE;
523                 return -1.0;
524         }
525
526         return adjust_data(strtol(buf, NULL, 10), chp->ch_type);
527 }
528
529 SR_PRIV int bl_acme_receive_data(int fd, int revents, void *cb_data)
530 {
531         uint32_t cur_time, elapsed_time, diff_time;
532         int64_t time_to_sleep;
533         struct sr_datafeed_packet packet, framep;
534         struct sr_datafeed_analog analog;
535         struct sr_dev_inst *sdi;
536         struct sr_channel *ch;
537         struct dev_context *devc;
538         GSList *chl, chonly;
539         float valf;
540
541         (void)fd;
542         (void)revents;
543
544         sdi = cb_data;
545         if (!sdi)
546                 return TRUE;
547
548         devc = sdi->priv;
549         if (!devc)
550                 return TRUE;
551
552         packet.type = SR_DF_ANALOG;
553         packet.payload = &analog;
554         memset(&analog, 0, sizeof(struct sr_datafeed_analog));
555         analog.data = &valf;
556
557         /*
558          * Reading from sysfs takes some time - try to keep up with samplerate.
559          */
560         if (devc->samples_read) {
561                 cur_time = g_get_monotonic_time();
562                 diff_time = cur_time - devc->last_sample_fin;
563                 time_to_sleep = G_USEC_PER_SEC / devc->samplerate - diff_time;
564                 if (time_to_sleep > 0)
565                         g_usleep(time_to_sleep);
566         }
567
568         framep.type = SR_DF_FRAME_BEGIN;
569         sr_session_send(cb_data, &framep);
570
571         /*
572          * Due to different units used in each channel we're sending
573          * samples one-by-one.
574          */
575         for (chl = sdi->channels; chl; chl = chl->next) {
576                 ch = chl->data;
577                 if (!ch->enabled)
578                         continue;
579                 chonly.next = NULL;
580                 chonly.data = ch;
581                 analog.channels = &chonly;
582                 analog.num_samples = 1;
583                 analog.mq = channel_to_mq(chl->data);
584                 analog.unit = channel_to_unit(ch);
585
586                 valf = read_sample(ch);
587
588                 sr_session_send(cb_data, &packet);
589         }
590
591         framep.type = SR_DF_FRAME_END;
592         sr_session_send(cb_data, &framep);
593
594         devc->samples_read++;
595         if (devc->limit_samples > 0 &&
596             devc->samples_read >= devc->limit_samples) {
597                 sr_info("Requested number of samples reached.");
598                 sdi->driver->dev_acquisition_stop(sdi, cb_data);
599                 devc->last_sample_fin = g_get_monotonic_time();
600                 return TRUE;
601         } else if (devc->limit_msec > 0) {
602                 cur_time = g_get_monotonic_time();
603                 elapsed_time = cur_time - devc->start_time;
604
605                 if (elapsed_time >= devc->limit_msec) {
606                         sr_info("Sampling time limit reached.");
607                         sdi->driver->dev_acquisition_stop(sdi, cb_data);
608                         devc->last_sample_fin = g_get_monotonic_time();
609                         return TRUE;
610                 }
611         }
612
613         devc->last_sample_fin = g_get_monotonic_time();
614         return TRUE;
615 }