#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

/* remote access through bidilink or socat */
char * scope_dev = "osc";

/* local access */
//char * scope_dev = "/dev/ttyS1";

int scope;

char answer[256];

void gds_ask(char * cmd)
{
	char c;
	int k;
	int ret;

	printf("%s ... ", cmd); fflush(stdout);
	ret = write(scope, cmd, strlen(cmd));
	if (ret == -1) {
		perror("write()");
		exit(1);
	};

	memset(answer, (int)0, 256);
	k = 0;
	do {
		ret = read(scope, &c, 1);
		if (ret == -1) {
			perror("read()");
			break;
		};
		printf("%c", c);
		answer[k++] = c;
	} while ( c != '\n' );
}

#include <termios.h>

int main(void)
{
	struct termios options;
	int r;

	printf("Opening %s ... ", scope_dev);
	fflush(stdout);

	scope = open(scope_dev, O_RDWR);
	if (scope == -1) {
		perror("open()");
		exit(1);
	};
	printf("OK\n");

	/* set raw mode for pty */
	r = tcgetattr(scope, &options);
	if (-1 == r) {
		perror("tcgetattr()");
		exit(1);
	}

	options.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
	options.c_oflag &= ~(OPOST);
	options.c_cflag |= (CS8);
	options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG | IEXTEN);

	r = tcsetattr(scope, TCSANOW, &options);
	if (-1 == r) {
		perror("tcsetattr()");
		exit(1);
	}

	gds_ask("*IDN?\n");
	exit(0);
}