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