1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2013 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 #include <config.h>
21 #include "protocol.h"
22 
23 #define LINE_LENGTH 20
24 
25 SR_PRIV const struct nmadmm_req nmadmm_requests[] = {
26 	{ NMADMM_REQ_IDN, "IDN?" },
27 	{ NMADMM_REQ_IDN, "STATUS?" },
28 	ALL_ZERO
29 };
30 
nma_send_req(const struct sr_dev_inst * sdi,int req,char * params)31 static int nma_send_req(const struct sr_dev_inst *sdi, int req, char *params)
32 {
33 	struct sr_serial_dev_inst *serial;
34 	struct dev_context *devc;
35 	char buf[NMADMM_BUFSIZE];
36 	int len;
37 
38 	if (!sdi || !(serial = sdi->conn) || !(devc = sdi->priv))
39 		return SR_ERR_BUG;
40 
41 	len = snprintf(buf, sizeof(buf), "%s%s\r\n",
42 		nmadmm_requests[req].req_str, params ? params : "");
43 
44 	sr_spew("Sending request: '%s'.", buf);
45 
46 	devc->last_req = req;
47 	devc->last_req_pending = TRUE;
48 
49 	if (serial_write_blocking(serial, buf, len,
50 			serial_timeout(serial, len)) < 0) {
51 		sr_err("Unable to send request.");
52 		devc->last_req_pending = FALSE;
53 		return SR_ERR;
54 	}
55 
56 	devc->req_sent_at = g_get_monotonic_time();
57 
58 	return SR_OK;
59 }
60 
61 /**
62  * Convert hexadecimal digit to int.
63  *
64  * @param[in] xgit Hexadecimal digit to convert.
65  * @return Int value of xgit (0 on invalid xgit).
66  */
xgittoint(char xgit)67 SR_PRIV int xgittoint(char xgit)
68 {
69 	if ((xgit >= '0') && (xgit <= '9'))
70 		return xgit - '0';
71 	xgit = tolower(xgit);
72 	if ((xgit >= 'a') && (xgit <= 'f'))
73 		return xgit - 'a';
74 	return 0;
75 }
76 
77 /**
78  * Process received line. It consists of 20 hex digits + \\r\\n,
79  * e.g. '08100400018100400000'.
80  */
nma_process_line(const struct sr_dev_inst * sdi)81 static void nma_process_line(const struct sr_dev_inst *sdi)
82 {
83 	struct dev_context *devc;
84 	int pos, flags;
85 	int vt, range;	/* Measurement value type, range in device format */
86 	int mmode, devstat;	/* Measuring mode, device status */
87 	float value;	/* Measured value */
88 	float scale;	/* Scaling factor depending on range and function */
89 	struct sr_datafeed_analog analog;
90 	struct sr_analog_encoding encoding;
91 	struct sr_analog_meaning meaning;
92 	struct sr_analog_spec spec;
93 	struct sr_datafeed_packet packet;
94 
95 	devc = sdi->priv;
96 
97 	devc->buf[LINE_LENGTH] = '\0';
98 
99 	sr_spew("Received line '%s'.", devc->buf);
100 
101 	/* Check line. */
102 	if (strlen((const char *)devc->buf) != LINE_LENGTH) {
103 		sr_err("line: Invalid status '%s', must be 20 hex digits.",
104 		       devc->buf);
105 		devc->buflen = 0;
106 		return;
107 	}
108 
109 	for (pos = 0; pos < LINE_LENGTH; pos++) {
110 		if (!isxdigit(devc->buf[pos])) {
111 			sr_err("line: Expected hex digit in '%s' at pos %d!",
112 				devc->buf, pos);
113 			devc->buflen = 0;
114 			return;
115 		}
116 	}
117 
118 	/* Start decoding. */
119 	value = 0.0;
120 	scale = 1.0;
121 	/* TODO: Use proper 'digits' value for this device (and its modes). */
122 	sr_analog_init(&analog, &encoding, &meaning, &spec, 2);
123 
124 	/*
125 	 * The numbers are hex digits, starting from 0.
126 	 * 0: Keyboard status, currently not interesting.
127 	 * 1: Central switch status, currently not interesting.
128 	 * 2: Type of measured value.
129 	 */
130 	vt = xgittoint(devc->buf[2]);
131 	switch (vt) {
132 	case 0:
133 		analog.meaning->mq = SR_MQ_VOLTAGE;
134 		break;
135 	case 1:
136 		analog.meaning->mq = SR_MQ_CURRENT;	/* 2A */
137 		break;
138 	case 2:
139 		analog.meaning->mq = SR_MQ_RESISTANCE;
140 		break;
141 	case 3:
142 		analog.meaning->mq = SR_MQ_CAPACITANCE;
143 		break;
144 	case 4:
145 		analog.meaning->mq = SR_MQ_TEMPERATURE;
146 		break;
147 	case 5:
148 		analog.meaning->mq = SR_MQ_FREQUENCY;
149 		break;
150 	case 6:
151 		analog.meaning->mq = SR_MQ_CURRENT;	/* 10A */
152 		break;
153 	case 7:
154 		analog.meaning->mq = SR_MQ_GAIN;		/* TODO: Scale factor */
155 		break;
156 	case 8:
157 		analog.meaning->mq = SR_MQ_GAIN;		/* Percentage */
158 		scale /= 100.0;
159 		break;
160 	case 9:
161 		analog.meaning->mq = SR_MQ_GAIN;		/* dB */
162 		scale /= 100.0;
163 		break;
164 	default:
165 		sr_err("Unknown value type: 0x%02x.", vt);
166 		break;
167 	}
168 
169 	/* 3: Measurement range for measured value */
170 	range = xgittoint(devc->buf[3]);
171 	switch (vt) {
172 	case 0: /* V */
173 		scale *= pow(10.0, range - 5);
174 		break;
175 	case 1: /* A */
176 		scale *= pow(10.0, range - 7);
177 		break;
178 	case 2: /* Ω */
179 		scale *= pow(10.0, range - 2);
180 		break;
181 	case 3: /* F */
182 		scale *= pow(10.0, range - 12);
183 		break;
184 	case 4: /* °C */
185 		scale *= pow(10.0, range - 1);
186 		break;
187 	case 5: /* Hz */
188 		scale *= pow(10.0, range - 2);
189 		break;
190 	// No default, other value types have fixed display format.
191 	}
192 
193 	/* 5: Sign and 1st digit */
194 	flags = xgittoint(devc->buf[5]);
195 	value = (flags & 0x03);
196 	if (flags & 0x04)
197 		scale *= -1;
198 
199 	/* 6-9: 2nd-4th digit */
200 	for (pos = 6; pos < 10; pos++)
201 		value = value * 10 + xgittoint(devc->buf[pos]);
202 	value *= scale;
203 
204 	/* 10: Display counter */
205 	mmode = xgittoint(devc->buf[10]);
206 	switch (mmode) {
207 	case 0: /* Frequency */
208 		analog.meaning->unit = SR_UNIT_HERTZ;
209 		break;
210 	case 1: /* V TRMS, only type 5 */
211 		analog.meaning->unit = SR_UNIT_VOLT;
212 		analog.meaning->mqflags |= (SR_MQFLAG_AC | SR_MQFLAG_DC | SR_MQFLAG_RMS);
213 		break;
214 	case 2: /* V AC */
215 		analog.meaning->unit = SR_UNIT_VOLT;
216 		analog.meaning->mqflags |= SR_MQFLAG_AC;
217 		if (devc->type >= 3)
218 			analog.meaning->mqflags |= SR_MQFLAG_RMS;
219 		break;
220 	case 3: /* V DC */
221 		analog.meaning->unit = SR_UNIT_VOLT;
222 		analog.meaning->mqflags |= SR_MQFLAG_DC;
223 		break;
224 	case 4: /* Ohm */
225 		analog.meaning->unit = SR_UNIT_OHM;
226 		break;
227 	case 5: /* Continuity */
228 		analog.meaning->unit = SR_UNIT_BOOLEAN;
229 		analog.meaning->mq = SR_MQ_CONTINUITY;
230 		/* TODO: Continuity handling is a bit odd in libsigrok. */
231 		break;
232 	case 6: /* Degree Celsius */
233 		analog.meaning->unit = SR_UNIT_CELSIUS;
234 		break;
235 	case 7: /* Capacity */
236 		analog.meaning->unit = SR_UNIT_FARAD;
237 		break;
238 	case 8: /* Current DC */
239 		analog.meaning->unit = SR_UNIT_AMPERE;
240 		analog.meaning->mqflags |= SR_MQFLAG_DC;
241 		break;
242 	case 9: /* Current AC */
243 		analog.meaning->unit = SR_UNIT_AMPERE;
244 		analog.meaning->mqflags |= SR_MQFLAG_AC;
245 		if (devc->type >= 3)
246 			analog.meaning->mqflags |= SR_MQFLAG_RMS;
247 		break;
248 	case 0xa: /* Current TRMS, only type 5 */
249 		analog.meaning->unit = SR_UNIT_AMPERE;
250 		analog.meaning->mqflags |= (SR_MQFLAG_AC | SR_MQFLAG_DC | SR_MQFLAG_RMS);
251 		break;
252 	case 0xb: /* Diode */
253 		analog.meaning->unit = SR_UNIT_VOLT;
254 		analog.meaning->mqflags |= (SR_MQFLAG_DIODE | SR_MQFLAG_DC);
255 		break;
256 	default:
257 		sr_err("Unknown mmode: 0x%02x.", mmode);
258 		break;
259 	}
260 
261 	/* 11: Device status */
262 	devstat = xgittoint(devc->buf[11]);
263 
264 	switch (devstat) {
265 	case 1: /* Normal measurement */
266 		break;
267 	case 2: /* Input loop (limit, reference values) */
268 		break;
269 	case 3: /* TRANS/SENS */
270 		break;
271 	case 4: /* Error */
272 		sr_err("Device error. Fuse?"); /* TODO: Really abort? */
273 		devc->buflen = 0;
274 		return;	/* Cannot continue. */
275 	default:
276 		sr_err("Unknown device status: 0x%02x", devstat);
277 		break;
278 	}
279 
280 	/* 12-19: Flags and display symbols */
281 	/* 12, 13 */
282 	flags = (xgittoint(devc->buf[12]) << 8) | xgittoint(devc->buf[13]);
283 	/* 0x80: PRINT TODO: Stop polling when discovered? */
284 	/* 0x40: EXTR */
285 	if (analog.meaning->mq == SR_MQ_CONTINUITY) {
286 		if (flags & 0x20)
287 			value = 1.0; /* Beep */
288 		else
289 			value = 0.0;
290 	}
291 	/* 0x10: AVG */
292 	/* 0x08: Diode */
293 	if (flags & 0x04) /* REL */
294 		analog.meaning->mqflags |= SR_MQFLAG_RELATIVE;
295 	/* 0x02: SHIFT	*/
296 	if (flags & 0x01) /* % */
297 		analog.meaning->unit = SR_UNIT_PERCENTAGE;
298 
299 	/* 14, 15 */
300 	flags = (xgittoint(devc->buf[14]) << 8) | xgittoint(devc->buf[15]);
301 	if (!(flags & 0x80))	/* MAN: Manual range */
302 		analog.meaning->mqflags |= SR_MQFLAG_AUTORANGE;
303 	if (flags & 0x40) /* LOBATT1: Low battery, measurement still within specs */
304 		devc->lowbatt = 1;
305 	/* 0x20: PEAK */
306 	/* 0x10: COUNT */
307 	if (flags & 0x08)	/* HOLD */
308 		analog.meaning->mqflags |= SR_MQFLAG_HOLD;
309 	/* 0x04: LIMIT	*/
310 	if (flags & 0x02) 	/* MAX */
311 		analog.meaning->mqflags |= SR_MQFLAG_MAX;
312 	if (flags & 0x01) 	/* MIN */
313 		analog.meaning->mqflags |= SR_MQFLAG_MIN;
314 
315 	/* 16, 17 */
316 	flags = (xgittoint(devc->buf[16]) << 8) | xgittoint(devc->buf[17]);
317 	/* 0xe0: undefined */
318 	if (flags & 0x10) { /* LOBATT2: Low battery, measurement inaccurate */
319 		devc->lowbatt = 2;
320 		sr_warn("Low battery, measurement quality degraded!");
321 	}
322 	/* 0x08: SCALED */
323 	/* 0x04: RATE (=lower resolution, allows higher data rate up to 10/s. */
324 	/* 0x02: Current clamp */
325 	if (flags & 0x01) { /* dB */
326 		/*
327 		 * TODO: The Norma has an adjustable dB reference value. If
328 		 * changed from default, this is not correct.
329 		 */
330 		if (analog.meaning->unit == SR_UNIT_VOLT)
331 			analog.meaning->unit = SR_UNIT_DECIBEL_VOLT;
332 		else
333 			analog.meaning->unit = SR_UNIT_UNITLESS;
334 	}
335 
336 	/* 18, 19 */
337 	/* flags = (xgittoint(devc->buf[18]) << 8) | xgittoint(devc->buf[19]); */
338 	/* 0x80: Undefined. */
339 	/* 0x40: Remote mode, keyboard locked */
340 	/* 0x38: Undefined. */
341 	/* 0x04: MIN > MAX */
342 	/* 0x02: Measured value < Min */
343 	/* 0x01: Measured value > Max */
344 
345 	/* 4: Flags. Evaluating this after setting value! */
346 	flags = xgittoint(devc->buf[4]);
347 	if (flags & 0x04) /* Invalid value */
348 		value = NAN;
349 	else if (flags & 0x01) /* Overload */
350 		value = INFINITY;
351 	if (flags & 0x02) { /* Duplicate value, has been sent before. */
352 		sr_spew("Duplicate value, dismissing!");
353 		devc->buflen = 0;
354 		return;
355 	}
356 
357 	sr_spew("range=%d/scale=%f/value=%f", range,
358 		(double)scale, (double)value);
359 
360 	/* Finish and send packet. */
361 	analog.meaning->channels = sdi->channels;
362 	analog.num_samples = 1;
363 	analog.data = &value;
364 
365 	memset(&packet, 0, sizeof(struct sr_datafeed_packet));
366 	packet.type = SR_DF_ANALOG;
367 	packet.payload = &analog;
368 	sr_session_send(sdi, &packet);
369 
370 	/* Finish processing. */
371 	sr_sw_limits_update_samples_read(&devc->limits, 1);
372 	devc->buflen = 0;
373 }
374 
norma_dmm_receive_data(int fd,int revents,void * cb_data)375 SR_PRIV int norma_dmm_receive_data(int fd, int revents, void *cb_data)
376 {
377 	struct sr_dev_inst *sdi;
378 	struct dev_context *devc;
379 	struct sr_serial_dev_inst *serial;
380 	int len;
381 
382 	(void)fd;
383 
384 	if (!(sdi = cb_data))
385 		return TRUE;
386 
387 	if (!(devc = sdi->priv))
388 		return TRUE;
389 
390 	serial = sdi->conn;
391 	if (revents == G_IO_IN) {
392 		/* Serial data arrived. */
393 		while (NMADMM_BUFSIZE - devc->buflen - 1 > 0) {
394 			len = serial_read_nonblocking(serial, devc->buf + devc->buflen, 1);
395 			if (len < 1)
396 				break;
397 			devc->buflen += len;
398 			*(devc->buf + devc->buflen) = '\0';
399 			if (*(devc->buf + devc->buflen - 1) == '\n') {
400 				/*
401 				 * TODO: According to specs, should be \r, but
402 				 * then we'd have to get rid of the \n.
403 				 */
404 				devc->last_req_pending = FALSE;
405 				nma_process_line(sdi);
406 				break;
407 			}
408 		}
409 	}
410 
411 	if (sr_sw_limits_check(&devc->limits)) {
412 		sr_dev_acquisition_stop(sdi);
413 	} else {
414 		/* Request next package. */
415 		if (devc->last_req_pending) {
416 			gint64 elapsed_us = g_get_monotonic_time() - devc->req_sent_at;
417 			if (elapsed_us > NMADMM_TIMEOUT_MS * 1000) {/* Timeout! */
418 				sr_spew("Request timeout!");
419 				devc->last_req_pending = FALSE;
420 			}
421 		}
422 		if (!devc->last_req_pending) {
423 			if (nma_send_req(sdi, NMADMM_REQ_STATUS, NULL) != SR_OK)
424 				return FALSE;
425 		}
426 	}
427 
428 	return TRUE;
429 }
430