view cmu200/sercmd.c @ 34:99f753d4ccaf

fc-cmu200d: check for errors on serial port write
author Mychaela Falconia <falcon@freecalypso.org>
date Tue, 23 May 2017 00:33:10 +0000
parents aeffe53e110d
children
line wrap: on
line source

/*
 * This module contains the functions that send serial commands to the CMU200
 * and collect the instrument's serial responses.
 */

#include <sys/types.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <strings.h>

extern int target_fd;

char instrument_response[4096];

send_scpi_cmd(cmd)
	char *cmd;
{
	int cc, len;

	printf("Command to CMU: %s", cmd);
	len = strlen(cmd);
	cc = write(target_fd, cmd, len);
	if (cc != len) {
		perror("serial port write error");
		exit(1);
	}
}

collect_instr_response()
{
	char buf[BUFSIZ];
	int cc, pos;

	for (pos = 0; ; ) {
		cc = read(target_fd, buf, sizeof buf);
		if (cc <= 0) {
			perror("error reading from serial port");
			exit(1);
		}
		if (pos + cc > sizeof instrument_response) {
			fprintf(stderr,
		"error: response from CMU200 exceeds our buffer size\n");
			exit(1);
		}
		bcopy(buf, instrument_response + pos, cc);
		pos += cc;
		if (instrument_response[pos-1] == '\n')
			break;
	}
	instrument_response[pos-1] = '\0';
	if (pos >= 2 && instrument_response[pos-2] == '\r')
		instrument_response[pos-2] = '\0';
	printf("Instrument response: %s\n", instrument_response);
}

collect_staropc_response()
{
	collect_instr_response();
	if (instrument_response[0] != '1' || instrument_response[1]) {
		fprintf(stderr, "error: unexpected response to *OPC?\n");
		exit(1);
	}
}

parse_commasep_response(argv, expect_count)
	char **argv;
{
	char *cp, *sp;
	int i;

	cp = instrument_response;
	for (i = 0; i < expect_count - 1; i++) {
		argv[i] = cp;
		sp = index(cp, ',');
		if (!sp)
			return(-1);
		*sp = '\0';
		cp = sp + 1;
	}
	argv[i] = cp;
	if (index(cp, ','))
		return(-1);
	return(0);
}