]> sigrok.org Git - libsigrok.git/blob - hardware/gmc-mh-1x-2x/api.c
build: Portability fixes.
[libsigrok.git] / hardware / gmc-mh-1x-2x / api.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2013, 2014 Matthias Heidbrink <m-sigrok@heidbrink.biz>
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 /** @file
21  *  Gossen Metrawatt Metrahit 1x/2x drivers
22  *  @internal
23  */
24
25 #include <string.h>
26 #include "protocol.h"
27
28 /* Serial communication parameters for Metrahit 1x/2x with 'RS232' adaptor */
29 #define SERIALCOMM_1X_RS232 "8228/6n1/dtr=1/rts=1/flow=0" /* =8192, closer with divider */
30 #define SERIALCOMM_2X_RS232 "9600/6n1/dtr=1/rts=1/flow=0"
31 #define SERIALCOMM_2X "9600/8n1/dtr=1/rts=1/flow=0"
32 #define VENDOR_GMC "Gossen Metrawatt"
33
34 SR_PRIV struct sr_dev_driver gmc_mh_1x_2x_rs232_driver_info;
35 SR_PRIV struct sr_dev_driver gmc_mh_2x_bd232_driver_info;
36
37 static const int32_t hwopts[] = {
38         SR_CONF_CONN,
39         SR_CONF_SERIALCOMM,
40 };
41
42 /** Hardware capabilities for Metrahit 1x/2x devices in send mode. */
43 static const int32_t hwcaps_sm[] = {
44         SR_CONF_MULTIMETER,
45         SR_CONF_THERMOMETER,    /**< All GMC 1x/2x multimeters seem to support this */
46         SR_CONF_LIMIT_SAMPLES,
47         SR_CONF_LIMIT_MSEC,
48         SR_CONF_CONTINUOUS,
49 };
50
51 /** Hardware capabilities for Metrahit 2x devices in bidirectional Mode. */
52 static const int32_t hwcaps_bd[] = {
53         SR_CONF_MULTIMETER,
54         SR_CONF_THERMOMETER,    /**< All GMC 1x/2x multimeters seem to support this */
55         SR_CONF_LIMIT_SAMPLES,
56         SR_CONF_LIMIT_MSEC,
57         SR_CONF_CONTINUOUS,
58         SR_CONF_POWER_OFF,
59 };
60
61
62 /* TODO:
63  * - For the 29S SR_CONF_ENERGYMETER, too.
64  * - SR_CONF_PATTERN_MODE for some 2x devices
65  * - SR_CONF_DATALOG for 22M, 26M, 29S and storage adaptors.
66  * Need to implement device-specific lists.
67  */
68
69 /** Init driver gmc_mh_1x_2x_rs232. */
70 static int init_1x_2x_rs232(struct sr_context *sr_ctx)
71 {
72         return std_init(sr_ctx, &gmc_mh_1x_2x_rs232_driver_info, LOG_PREFIX);
73 }
74
75 /** Init driver gmc_mh_2x_bd232. */
76 static int init_2x_bd232(struct sr_context *sr_ctx)
77 {
78         return std_init(sr_ctx, &gmc_mh_2x_bd232_driver_info, LOG_PREFIX);
79 }
80
81 /**
82  * Read single byte from serial port.
83  *
84  * @retval -1 Timeout or error.
85  * @retval other Byte.
86  */
87 static int read_byte(struct sr_serial_dev_inst *serial, gint64 timeout)
88 {
89         uint8_t result = 0;
90         int rc = 0;
91
92         for (;;) {
93                 rc = serial_read(serial, &result, 1);
94                 if (rc == 1) {
95                         sr_spew("read: 0x%02x/%d", result, result);
96                         return result;
97                 }
98                 if (g_get_monotonic_time() > timeout)
99                         return -1;
100                 g_usleep(2000);
101         }
102 }
103
104 /**
105  * Try to detect GMC 1x/2x multimeter model in send mode for max. 1 second.
106  *
107  * @param serial Configured, open serial port.
108  *
109  * @retval NULL Detection failed.
110  * @retval other Model code.
111  */
112 static enum model scan_model_sm(struct sr_serial_dev_inst *serial)
113 {
114         int byte, bytecnt, cnt;
115         enum model model;
116         gint64 timeout_us;
117
118         model = METRAHIT_NONE;
119         timeout_us = g_get_monotonic_time() + 1 * 1000 * 1000;
120
121         /*
122          * Try to find message consisting of device code and several
123          * (at least 4) data bytes.
124          */
125         for (bytecnt = 0; bytecnt < 100; bytecnt++) {
126                 byte = read_byte(serial, timeout_us);
127                 if ((byte == -1) || (timeout_us < g_get_monotonic_time()))
128                         break;
129                 if ((byte & MSGID_MASK) == MSGID_INF) {
130                         if (!(model = gmc_decode_model_sm(byte & MSGC_MASK)))
131                                 break;
132                         /* Now expect (at least) 4 data bytes. */
133                         for (cnt = 0; cnt < 4; cnt++) {
134                                 byte = read_byte(serial, timeout_us);
135                                 if ((byte == -1) ||
136                                                 ((byte & MSGID_MASK) != MSGID_DATA))
137                                 {
138                                         model = METRAHIT_NONE;
139                                         bytecnt = 100;
140                                         break;
141                                 }
142                         }
143                         break;
144                 }
145         }
146
147         return model;
148 }
149
150 /**
151  * Scan for Metrahit 1x and Metrahit 2x in send mode using Gossen Metrawatt
152  * 'RS232' interface.
153  *
154  * The older 1x models use 8192 baud and the newer 2x 9600 baud.
155  * The DMM usually sends up to about 20 messages per second. However, depending
156  * on configuration and measurement mode the intervals can be much larger and
157  * then the detection might not work.
158  */
159 static GSList *scan_1x_2x_rs232(GSList *options)
160 {
161         struct sr_dev_inst *sdi;
162         struct drv_context *drvc;
163         struct dev_context *devc;
164         struct sr_config *src;
165         struct sr_channel *ch;
166         struct sr_serial_dev_inst *serial;
167         GSList *l, *devices;
168         const char *conn, *serialcomm;
169         enum model model;
170         gboolean serialcomm_given;
171
172         devices = NULL;
173         drvc = (&gmc_mh_1x_2x_rs232_driver_info)->priv;
174         drvc->instances = NULL;
175         conn = serialcomm = NULL;
176         model = METRAHIT_NONE;
177         serialcomm_given = FALSE;
178
179         sr_spew("scan_1x_2x_rs232() called!");
180
181         for (l = options; l; l = l->next) {
182                 src = l->data;
183                 switch (src->key) {
184                 case SR_CONF_CONN:
185                         conn = g_variant_get_string(src->data, NULL);
186                         break;
187                 case SR_CONF_SERIALCOMM:
188                         serialcomm = g_variant_get_string(src->data, NULL);
189                         serialcomm_given = TRUE;
190                         break;
191                 }
192         }
193         if (!conn)
194                 return NULL;
195         if (!serialcomm)
196                 serialcomm = SERIALCOMM_2X_RS232;
197
198         if (!(serial = sr_serial_dev_inst_new(conn, serialcomm)))
199                 return NULL;
200
201         if (serial_open(serial, SERIAL_RDWR | SERIAL_NONBLOCK) != SR_OK) {
202                 sr_serial_dev_inst_free(serial);
203                 return NULL;
204         }
205
206         serial_flush(serial);
207
208         model = scan_model_sm(serial);
209
210         /*
211          * If detection failed and no user-supplied parameters,
212          * try second baud rate.
213          */
214         if ((model == METRAHIT_NONE) && !serialcomm_given) {
215                 serialcomm = SERIALCOMM_1X_RS232;
216                 g_free(serial->serialcomm);
217                 serial->serialcomm = g_strdup(serialcomm);
218                 if (serial_set_paramstr(serial, serialcomm) == SR_OK) {
219                         serial_flush(serial);
220                         model = scan_model_sm(serial);
221                 }
222         }
223
224         if (model != METRAHIT_NONE) {
225                 sr_spew("%s %s detected!", VENDOR_GMC, gmc_model_str(model));
226                 if (!(sdi = sr_dev_inst_new(0, SR_ST_INACTIVE, VENDOR_GMC,
227                                 gmc_model_str(model), NULL)))
228                         return NULL;
229                 if (!(devc = g_try_malloc0(sizeof(struct dev_context)))) {
230                         sr_err("Device context malloc failed.");
231                         return NULL;
232                 }
233                 devc->model = model;
234                 devc->limit_samples = 0;
235                 devc->limit_msec = 0;
236                 devc->num_samples = 0;
237                 devc->elapsed_msec = g_timer_new();
238                 devc->settings_ok = FALSE;
239
240                 sdi->conn = serial;
241                 sdi->priv = devc;
242                 sdi->driver = &gmc_mh_1x_2x_rs232_driver_info;
243                 if (!(ch = sr_channel_new(0, SR_CHANNEL_ANALOG, TRUE, "P1")))
244                         return NULL;
245                 sdi->channels = g_slist_append(sdi->channels, ch);
246                 drvc->instances = g_slist_append(drvc->instances, sdi);
247                 devices = g_slist_append(devices, sdi);
248         }
249
250         return devices;
251 }
252
253 /** Scan for Metrahit 2x in a bidirectional mode using Gossen Metrawatt 'BD 232' interface.
254  *
255  */
256 static GSList *scan_2x_bd232(GSList *options)
257 {
258         struct sr_dev_inst *sdi;
259         struct drv_context *drvc;
260         struct dev_context *devc;
261         struct sr_config *src;
262         struct sr_channel *ch;
263         struct sr_serial_dev_inst *serial;
264         GSList *l, *devices;
265         const char *conn, *serialcomm;
266         int cnt, byte;
267         gint64 timeout_us;
268
269         sdi = NULL;
270         devc = NULL;
271         conn = serialcomm = NULL;
272         devices = NULL;
273
274         drvc = (&gmc_mh_2x_bd232_driver_info)->priv;
275         drvc->instances = NULL;
276
277         sr_spew("scan_2x_bd232() called!");
278
279         for (l = options; l; l = l->next) {
280                 src = l->data;
281                 switch (src->key) {
282                 case SR_CONF_CONN:
283                         conn = g_variant_get_string(src->data, NULL);
284                         break;
285                 case SR_CONF_SERIALCOMM:
286                         serialcomm = g_variant_get_string(src->data, NULL);
287                         break;
288                 }
289         }
290         if (!conn)
291                 return NULL;
292         if (!serialcomm)
293                 serialcomm = SERIALCOMM_2X;
294
295         if (!(serial = sr_serial_dev_inst_new(conn, serialcomm)))
296                 return NULL;
297
298         if (serial_open(serial, SERIAL_RDWR | SERIAL_NONBLOCK) != SR_OK)
299                 goto exit_err;
300
301         if (!(devc = g_try_malloc0(sizeof(struct dev_context)))) {
302                 sr_err("Device context malloc failed.");
303                 goto exit_err;
304         }
305
306         if (!(sdi = sr_dev_inst_new(0, SR_ST_INACTIVE, VENDOR_GMC, NULL, NULL)))
307                 goto exit_err;
308
309         sdi->priv = devc;
310
311         /* Send message 03 "Query multimeter version and status" */
312         sdi->conn = serial;
313         sdi->priv = devc;
314         if (req_stat14(sdi, TRUE) != SR_OK)
315                 goto exit_err;
316
317         /* Wait for reply from device(s) for up to 2s. */
318         timeout_us = g_get_monotonic_time() + 2*1000*1000;
319
320         while (timeout_us > g_get_monotonic_time()) {
321                 /* Receive reply (14 bytes) */
322                 devc->buflen = 0;
323                 for (cnt = 0; cnt < 14; cnt++) {
324                         byte = read_byte(serial, timeout_us);
325                         if (byte != -1)
326                                 devc->buf[devc->buflen++] = (byte & MASK_6BITS);
327                 }
328
329                 if (devc->buflen != 14)
330                         continue;
331
332                 devc->addr = devc->buf[0];
333                 process_msg14(sdi);
334                 devc->buflen = 0;
335
336                 if (devc->model != METRAHIT_NONE) {
337                         sr_spew("%s %s detected!", VENDOR_GMC, gmc_model_str(devc->model));
338
339                         devc->elapsed_msec = g_timer_new();
340
341                         sdi->model = g_strdup(gmc_model_str(devc->model));
342                         sdi->version = g_strdup_printf("Firmware %d.%d", devc->fw_ver_maj, devc->fw_ver_min);
343                         sdi->conn = serial;
344                         sdi->priv = devc;
345                         sdi->driver = &gmc_mh_2x_bd232_driver_info;
346                         if (!(ch = sr_channel_new(0, SR_CHANNEL_ANALOG, TRUE, "P1")))
347                                 goto exit_err;
348                         sdi->channels = g_slist_append(sdi->channels, ch);
349                         drvc->instances = g_slist_append(drvc->instances, sdi);
350                         devices = g_slist_append(devices, sdi);
351
352                         if (!(devc = g_try_malloc0(sizeof(struct dev_context)))) {
353                                 sr_err("Device context malloc failed.");
354                                 goto exit_err;
355                         }
356
357                         if (!(sdi = sr_dev_inst_new(0, SR_ST_INACTIVE, VENDOR_GMC, NULL, NULL)))
358                                 goto exit_err;
359                 }
360         };
361
362         /* Free last alloc if no device found */
363         if (devc->model == METRAHIT_NONE) {
364                 g_free(devc);
365                 sr_dev_inst_free(sdi);
366         }
367
368         return devices;
369
370 exit_err:
371         sr_info("scan_2x_bd232(): Error!");
372
373         if (serial)
374                 sr_serial_dev_inst_free(serial);
375         if (devc)
376                 g_free(devc);
377         if (sdi)
378                 sr_dev_inst_free(sdi);
379
380         return NULL;
381 }
382
383 /** Driver device list function */
384 static GSList *dev_list_1x_2x_rs232(void)
385 {
386         return ((struct drv_context *)(gmc_mh_1x_2x_rs232_driver_info.priv))->instances;
387 }
388
389 /** Driver device list function */
390 static GSList *dev_list_2x_bd232(void)
391 {
392         return ((struct drv_context *)(gmc_mh_2x_bd232_driver_info.priv))
393                         ->instances;
394 }
395
396 static int dev_close(struct sr_dev_inst *sdi)
397 {
398         struct dev_context *devc;
399
400         std_serial_dev_close(sdi);
401
402         sdi->status = SR_ST_INACTIVE;
403
404         /* Free dynamically allocated resources. */
405         if ((devc = sdi->priv) && devc->elapsed_msec) {
406                 g_timer_destroy(devc->elapsed_msec);
407                 devc->elapsed_msec = NULL;
408                 devc->model = METRAHIT_NONE;
409         }
410
411         return SR_OK;
412 }
413
414 static int cleanup_sm_rs232(void)
415 {
416         return std_dev_clear(&gmc_mh_1x_2x_rs232_driver_info, NULL);
417 }
418
419 static int cleanup_2x_bd232(void)
420 {
421         return std_dev_clear(&gmc_mh_2x_bd232_driver_info, NULL);
422 }
423
424 /** Get value of configuration item */
425 static int config_get(int key, GVariant **data, const struct sr_dev_inst *sdi,
426                       const struct sr_channel_group *cg)
427 {
428         int ret;
429         struct dev_context *devc;
430
431         (void)cg;
432
433         ret = SR_OK;
434
435         if (!sdi || !(devc = sdi->priv))
436                 return SR_ERR_ARG;
437
438         ret = SR_OK;
439         switch (key) {
440         case SR_CONF_LIMIT_SAMPLES:
441                 *data = g_variant_new_uint64(devc->limit_samples);
442                 break;
443         case SR_CONF_LIMIT_MSEC:
444                 *data = g_variant_new_uint64(devc->limit_msec);
445                 break;
446         case SR_CONF_POWER_OFF:
447                 *data = g_variant_new_boolean(FALSE);
448                 break;
449         default:
450                 return SR_ERR_NA;
451         }
452
453         return ret;
454 }
455
456 /** Implementation of config_list, auxiliary function for common parts, */
457 static int config_list_common(int key, GVariant **data, const struct sr_dev_inst *sdi,
458                               const struct sr_channel_group *cg)
459 {
460         (void)sdi;
461         (void)cg;
462
463         switch (key) {
464         case SR_CONF_SCAN_OPTIONS:
465                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_INT32,
466                                                   hwopts, ARRAY_SIZE(hwopts), sizeof(int32_t));
467                 break;
468         default:
469                 return SR_ERR_NA;
470         }
471
472         return SR_OK;
473 }
474
475 /** Implementation of config_list for Metrahit 1x/2x send mode */
476 static int config_list_sm(int key, GVariant **data, const struct sr_dev_inst *sdi,
477                           const struct sr_channel_group *cg)
478 {
479         switch (key) {
480         case SR_CONF_DEVICE_OPTIONS:
481                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_INT32,
482                                                   hwcaps_sm, ARRAY_SIZE(hwcaps_sm), sizeof(int32_t));
483                 break;
484         default:
485                 return config_list_common(key, data, sdi, cg);
486         }
487
488         return SR_OK;
489 }
490
491 /** Implementation of config_list for Metrahit 2x bidirectional mode */
492 static int config_list_bd(int key, GVariant **data, const struct sr_dev_inst *sdi,
493                           const struct sr_channel_group *cg)
494 {
495         switch (key) {
496         case SR_CONF_DEVICE_OPTIONS:
497                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_INT32,
498                                                   hwcaps_bd, ARRAY_SIZE(hwcaps_bd), sizeof(int32_t));
499                 break;
500         default:
501                 return config_list_common(key, data, sdi, cg);
502         }
503
504         return SR_OK;
505 }
506
507 static int dev_acquisition_start_1x_2x_rs232(const struct sr_dev_inst *sdi,
508                                              void *cb_data)
509 {
510         struct dev_context *devc;
511         struct sr_serial_dev_inst *serial;
512
513         if (!sdi || !cb_data || !(devc = sdi->priv))
514                 return SR_ERR_BUG;
515
516         if (sdi->status != SR_ST_ACTIVE)
517                 return SR_ERR_DEV_CLOSED;
518
519         devc->cb_data = cb_data;
520         devc->settings_ok = FALSE;
521         devc->buflen = 0;
522
523         /* Send header packet to the session bus. */
524         std_session_send_df_header(cb_data, LOG_PREFIX);
525
526         /* Start timer, if required. */
527         if (devc->limit_msec)
528                 g_timer_start(devc->elapsed_msec);
529
530         /* Poll every 40ms, or whenever some data comes in. */
531         serial = sdi->conn;
532         serial_source_add(sdi->session, serial, G_IO_IN, 40,
533                         gmc_mh_1x_2x_receive_data, (void *)sdi);
534
535         return SR_OK;
536 }
537
538 static int dev_acquisition_start_2x_bd232(const struct sr_dev_inst *sdi,
539                                           void *cb_data)
540 {
541         struct dev_context *devc;
542         struct sr_serial_dev_inst *serial;
543
544         if (!sdi || !cb_data || !(devc = sdi->priv))
545                 return SR_ERR_BUG;
546
547         if (sdi->status != SR_ST_ACTIVE)
548                 return SR_ERR_DEV_CLOSED;
549
550         devc->cb_data = cb_data;
551         devc->settings_ok = FALSE;
552         devc->buflen = 0;
553
554         /* Send header packet to the session bus. */
555         std_session_send_df_header(cb_data, LOG_PREFIX);
556
557         /* Start timer, if required. */
558         if (devc->limit_msec)
559                 g_timer_start(devc->elapsed_msec);
560
561         /* Poll every 40ms, or whenever some data comes in. */
562         serial = sdi->conn;
563         serial_source_add(sdi->session, serial, G_IO_IN, 40,
564                         gmc_mh_2x_receive_data, (void *)sdi);
565
566         /* Send start message */
567         return req_meas14(sdi);
568 }
569
570 static int dev_acquisition_stop(struct sr_dev_inst *sdi, void *cb_data)
571 {
572         struct dev_context *devc;
573
574         /* Stop timer, if required. */
575         if (sdi && (devc = sdi->priv) && devc->limit_msec)
576                 g_timer_stop(devc->elapsed_msec);
577
578         return std_serial_dev_acquisition_stop(sdi, cb_data, dev_close,
579                         sdi->conn, LOG_PREFIX);
580 }
581
582 SR_PRIV struct sr_dev_driver gmc_mh_1x_2x_rs232_driver_info = {
583         .name = "gmc-mh-1x-2x-rs232",
584         .longname = "Gossen Metrawatt Metrahit 1x/2x, RS232 interface",
585         .api_version = 1,
586         .init = init_1x_2x_rs232,
587         .cleanup = cleanup_sm_rs232,
588         .scan = scan_1x_2x_rs232,
589         .dev_list = dev_list_1x_2x_rs232,
590         .dev_clear = NULL,
591         .config_get = config_get,
592         .config_set = config_set,
593         .config_list = config_list_sm,
594         .dev_open = std_serial_dev_open,
595         .dev_close = dev_close,
596         .dev_acquisition_start = dev_acquisition_start_1x_2x_rs232,
597         .dev_acquisition_stop = dev_acquisition_stop,
598         .priv = NULL,
599 };
600
601 SR_PRIV struct sr_dev_driver gmc_mh_2x_bd232_driver_info = {
602         .name = "gmc-mh-2x-bd232",
603         .longname = "Gossen Metrawatt Metrahit 2x, BD232/SI232-II interface",
604         .api_version = 1,
605         .init = init_2x_bd232,
606         .cleanup = cleanup_2x_bd232,
607         .scan = scan_2x_bd232,
608         .dev_list = dev_list_2x_bd232,
609         .dev_clear = NULL,
610         .config_get = config_get,
611         .config_set = config_set,
612         .config_list = config_list_bd,
613         .dev_open = std_serial_dev_open,
614         .dev_close = dev_close,
615         .dev_acquisition_start = dev_acquisition_start_2x_bd232,
616         .dev_acquisition_stop = dev_acquisition_stop,
617         .priv = NULL,
618 };