<repo_name>mstramb/irmc<file_sep>/src/cwprotocol.c
#include <stdio.h>
#include "cwprotocol.h"

int prepare_id (struct data_packet_format *id_packet, char *id)
{
	id_packet->command = DAT;
	id_packet->length = SIZE_DATA_PACKET_PAYLOAD;
	snprintf(id_packet->id, SIZE_ID, id, "%s");
	id_packet->sequence = 0;
	id_packet->n = 0;
	snprintf(id_packet->status, SIZE_ID, INTERFACE_VERSION);
	id_packet->a21 = 1;     /* These magic numbers was provided by Les Kerr */
	id_packet->a22 = 755;
	id_packet->a23 = 65535;

	return 0;
}


int prepare_tx (struct data_packet_format *tx_packet, char *id)
{
	int i;

	tx_packet->command = DAT;
	tx_packet->length = SIZE_DATA_PACKET_PAYLOAD;
	snprintf(tx_packet->id, SIZE_ID,  id, "%s");
	tx_packet->sequence = 0;
	tx_packet->n = 0;
	for(i = 1; i < 51; i++)tx_packet->code[i] = 0;
	tx_packet->a21 = 0; /* These magic numbers was provided by Les Kerr */
	tx_packet->a22 = 755;
	tx_packet->a23 = 16777215;
	snprintf(tx_packet->status, SIZE_STATUS, "?");
	
	return 0;
}
<file_sep>/src/irmc.c
/* irmc - internet relay morsecode client */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <math.h>
#include <fcntl.h>
#include <morse/beep.h>
#ifdef __MACH__
#define LIBOSS_INTERNAL
#include <liboss/soundcard.h> //will not be used for audio any more
#else
#include <linux/ioctl.h>
#include <asm-generic/ioctl.h>
#include <asm-generic/termios.h>
#endif 
#include <signal.h>
#include <arpa/inet.h>
#include <time.h>
#include <sys/time.h>
#include <stdio.h>
 
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif
 
#define DEBUG 0

#define MAXDATASIZE 1024 // max number of bytes we can get at once 

#include "cwprotocol.h"
struct command_packet_format connect_packet = {CON, DEFAULT_CHANNEL}; 
struct command_packet_format disconnect_packet = {DIS, 0};
struct data_packet_format id_packet;
struct data_packet_format rx_data_packet;
struct data_packet_format tx_data_packet;

int serial_status = 0, fd_serial, fd_socket, numbytes;
int tx_sequence = 0, rx_sequence;

double tx_timeout = 0;
long tx_timer = 0;
#define TX_WAIT  5000
#define TX_TIMEOUT 240.0 
#define KEEPALIVE_CYCLE 100

long key_press_t1;
long key_release_t1;
int last_message = 0;
char last_sender[16];

/* settings */
int translate = 0;
int audio_status = 1;

/* portable time, as listed in https://gist.github.com/jbenet/1087739  */
void current_utc_time(struct timespec *ts) {
#ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time
  clock_serv_t cclock;
  mach_timespec_t mts;
  host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
  clock_get_time(cclock, &mts);
  mach_port_deallocate(mach_task_self(), cclock);
  ts->tv_sec = mts.tv_sec;
  ts->tv_nsec = mts.tv_nsec;
#else
  clock_gettime(CLOCK_REALTIME, ts);
#endif
 
}

/* a better clock() in milliseconds */
long 
fastclock(void)
{
	struct timespec t;
	long r;

	current_utc_time (&t);
	r = t.tv_sec * 1000;
	r = r + t.tv_nsec / 1000000;
	return r;
}

int kbhit (void)
{
  	struct timeval tv;
  	fd_set rdfs;

  	tv.tv_sec = 0;
  	tv.tv_usec = 0;

  	FD_ZERO(&rdfs);
  	FD_SET (STDIN_FILENO, &rdfs);

  	select (STDIN_FILENO+1, &rdfs, NULL, NULL, &tv);
  	return FD_ISSET(STDIN_FILENO, &rdfs);

}


/* get sockaddr, IPv4 or IPv6: */
void *get_in_addr(struct sockaddr *sa)
{
	if (sa->sa_family == AF_INET) {
		return &(((struct sockaddr_in*)sa)->sin_addr);
	}

	return &(((struct sockaddr_in6*)sa)->sin6_addr);
}

// connect to server and send my id.
void
identifyclient(void)
{
	tx_sequence++;
	id_packet.sequence = tx_sequence;
	send(fd_socket, &connect_packet, SIZE_COMMAND_PACKET, 0);
	send(fd_socket, &id_packet, SIZE_DATA_PACKET, 0);
}

// disconnect from the server
void
inthandler(int sig)
{
	signal(sig, SIG_IGN);
	send(fd_socket, &disconnect_packet, SIZE_COMMAND_PACKET, 0);	
	close(fd_socket);
	close(fd_serial);
	exit(1);
}

void
txloop (void)
{
	key_press_t1 = fastclock();
	tx_timeout = 0;
	for(;;){
		tx_data_packet.n++;
		tx_data_packet.code[tx_data_packet.n - 1] = 
			(int) ((key_press_t1 - key_release_t1) * -1);

		//printf("space: %i\n", tx_data_packet.code[tx_data_packet.n -1]);
		while(serial_status & TIOCM_DSR) ioctl(fd_serial, TIOCMGET, &serial_status);
		key_release_t1 = fastclock();

		tx_data_packet.n++;	
		tx_data_packet.code[tx_data_packet.n - 1] =
			(int) ((key_release_t1 - key_press_t1) * 1);
		
		//printf("mark: %i\n", tx_data_packet.code[tx_data_packet.n -1]);
		while(1){
			ioctl(fd_serial, TIOCMGET, &serial_status);
			if(serial_status & TIOCM_DSR) break;
			tx_timeout = fastclock() - key_release_t1;
			if(tx_timeout > TX_TIMEOUT) return;
		}
		key_press_t1 = fastclock();	
		if(tx_data_packet.n == SIZE_CODE) {
			printf("irmc: warning packet is full.\n");
			return;
		}
	}
}

int
commandmode(void)
{
	char cmd[32];
	int i;

	last_message = 0; /* reset status message */
	printf(".");
	fgets(cmd, 32, stdin);
	if(strncmp(cmd, ".", 1) == 0){
		printf("\n");
		return 1;
	}
	if((strncmp(cmd, "latch", 3)) == 0){
		tx_sequence++;
		tx_data_packet.sequence = tx_sequence;
		tx_data_packet.code[0] = -1;
		tx_data_packet.code[1] = 1;
		tx_data_packet.n = 2;
		for(i = 0; i < 5; i++) send(fd_socket, &tx_data_packet, SIZE_DATA_PACKET, 0);
		tx_data_packet.n = 0;
		return 0;
	}

	if((strncmp(cmd, "unlatch", 3)) == 0){
		tx_sequence++;
		tx_data_packet.sequence = tx_sequence;
		tx_data_packet.code[0] = -1;
		tx_data_packet.code[1] = 2;
		tx_data_packet.n = 2;
		for(i = 0; i < 5; i++) send(fd_socket, &tx_data_packet, SIZE_DATA_PACKET, 0);
		tx_data_packet.n = 0;
		return 0;
	}
	if((strncmp(cmd, "ton", 3)) == 0){
		translate = 1;
		return 0;
	}
	if((strncmp(cmd, "toff", 3)) == 0){
		translate = 0;
		return 0;
	}
	
	if((strncmp(cmd, "aon", 3)) == 0){
		audio_status = 1;
		return 0;
	}
	if((strncmp(cmd, "aoff", 3)) == 0){
		audio_status = 0;
		return 0;
	}
	printf("?\n");
	return 0;
}


void
message(int msg)
{       
	switch(msg){
	case 1:
		if(last_message == msg) return;
		if(last_message == 2) printf("\n");
		last_message = msg;
		printf("irmc: transmitting...\n");
		break;
	case 2:
		if(last_message == msg && strncmp(last_sender, rx_data_packet.id, 3) == 0) return;
		else {
			if(last_message == 2) printf("\n");
			last_message = msg;
			strncpy(last_sender, rx_data_packet.id, 3);
			printf("irmc: receiving...(%s)\n", rx_data_packet.id);
		}
		break;
	case 3:
		printf("irmc: circuit was latched by %s.\n", rx_data_packet.id);
		break;
	case 4:
		printf("irmc: circuit was unlatched by %s.\n", rx_data_packet.id);
		break;
	default:
		break;
	}
	fflush(0);
}
	 
int main(int argc, char *argv[])
{
	char buf[MAXDATASIZE];
	struct addrinfo hints, *servinfo, *p;
	int rv, i;
	char s[INET6_ADDRSTRLEN];
	int keepalive_t = 0;
	char hostname[64];
	char port[16];
	int channel;
	char id[SIZE_ID];
	char serialport[64];

	// Set default values
	snprintf(hostname, 64, "mtc-kob.dyndns.org");
	snprintf(port, 16, "7890");
	channel = 103;
	snprintf(id, SIZE_ID, "irmc-default");
	snprintf(serialport, 64, "/dev/tty.usbserial");

	// Read commandline
	opterr = 0; 
	int c;
	while ((c = getopt (argc, argv, "h:p:c:i:s:")) != -1)
	{
		switch (c) 
		{
			case 'h':
				snprintf(hostname, 64, "%s", optarg);
				break;
			case 'p':
				snprintf(port, 16, "%s", optarg);
				break;
			case 'c':
				channel = atoi (optarg);
				break;
			case 'i':
				snprintf(id, SIZE_ID, "%s", optarg);
				break;
			case 's':
				snprintf(serialport, 64, "%s", optarg);
				break;
			case '?':
	    			fprintf(stderr, "irmc - Internet Relay Morse Code\n\n");
				fprintf(stderr, "usage: irmc [arguments]\n\n");
				fprintf(stderr, "Arguments:\n\n");
				fprintf(stderr, "   -h [hostname]     Hostname of morsekob server. Default: %s\n", hostname);
				fprintf(stderr, "   -p [port]         Port of morsekob server. Default: %s\n", port);
				fprintf(stderr, "   -c [channel]      Channel. Default: %d\n", channel);
				fprintf(stderr, "   -i [id]           My ID. Default: %s\n", id);
				fprintf(stderr, "   -s [serialport]   Serial port device name. Default: %s\n", serialport);
				return 1;
			default: 
				abort ();
		}
	}

	// Preparing connection
	fprintf(stderr, "irmc - Internet Relay Morse Code\n\n");
	fprintf(stderr, "Connecting to %s:%s on channel %d with ID %s.\n", hostname, port, channel, id); 

	prepare_id (&id_packet, id);
	prepare_tx (&tx_data_packet, id);
	connect_packet.channel = channel;
	
	signal(SIGINT, inthandler);
	
	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC; /* ipv4 or ipv6 */
	hints.ai_socktype = SOCK_DGRAM;

	if ((rv = getaddrinfo(hostname, port, &hints, &servinfo)) != 0) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
		return 1;
	}
	
	/* Find the first free socket */
	for(p = servinfo; p != NULL; p = p->ai_next) {
		if ((fd_socket = socket(p->ai_family, p->ai_socktype,
			p->ai_protocol)) == -1) {
			perror("irmc: socket");
			continue;
		}

		if (connect(fd_socket, p->ai_addr, p->ai_addrlen) == -1) {
			close(fd_socket);
			perror("irmc: connect");
			continue;
		}

		break;
	}
    
    
    	fcntl(fd_socket, F_SETFL, O_NONBLOCK);
	if (p == NULL) {
		fprintf(stderr, "Failed to connect.\n");
		return 2;
	}

	inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
			s, sizeof s);
	fprintf(stderr, "Connected to %s.\n", s);
	beep_init();
	fd_serial = open(serialport, O_RDWR | O_NOCTTY | O_NDELAY);
	if(fd_serial == -1) {
    		fprintf(stderr,"Unable to open serial port %s.\n", serialport);
    	}
	freeaddrinfo(servinfo); /* all done with this structure */

	key_release_t1 = fastclock();
	identifyclient();
    
	/* Main Loop */
	for(;;) {
  		if(tx_timer == 0) 
			if((numbytes = recv(fd_socket, buf, MAXDATASIZE-1, 0)) == -1)
				usleep(250);
		if(numbytes == SIZE_DATA_PACKET && tx_timer == 0){
			memcpy(&rx_data_packet, buf, SIZE_DATA_PACKET);
		#if DEBUG  
			printf("length: %i\n", rx_data_packet.length);
			printf("id: %s\n", rx_data_packet.id);
			printf("sequence no.: %i\n", rx_data_packet.sequence);
			printf("version: %s\n", rx_data_packet.status);
			printf("n: %i\n", rx_data_packet.n);
			printf("code:\n");
			for(i = 0; i < SIZE_CODE; i++)printf("%i ", rx_data_packet.code[i]); printf("\n");
		#endif
			if(rx_data_packet.n > 0 && rx_sequence != rx_data_packet.sequence){
				message(2);
				if(translate == 1){
					printf("%s", rx_data_packet.status);
					fflush(0);
				}
				rx_sequence = rx_data_packet.sequence;
				for(i = 0; i < rx_data_packet.n; i++){
					switch(rx_data_packet.code[i]){
					case 1:
						message(3);
						break;
					case 2:
						message(4);
						break;
					default:
						if(audio_status == 1)
						{ 

							int length = rx_data_packet.code[i];
							if(length == 0 || abs(length) > 2000) {
							}
							else
							{
								if(length < 0) {
									beep(0.0, abs(length)/1000.);
								}
								else
								{
									beep(1000.0, length/1000.);
								}
							}
						}
						break;
					}
				}
			}
		}
	
		if(tx_timer > 0) tx_timer--;
		if(tx_data_packet.n > 1 ){
			tx_sequence++;
			tx_data_packet.sequence = tx_sequence;
			for(i = 0; i < 5; i++) send(fd_socket, &tx_data_packet, SIZE_DATA_PACKET, 0);
		#if DEBUG		
			printf("irmc: sent data packet.\n");
		#endif
			tx_data_packet.n = 0;
		}
		ioctl(fd_serial,TIOCMGET, &serial_status);
		if(serial_status & TIOCM_DSR){
			txloop();
			tx_timer = TX_WAIT;
			message(1);
		}
		
		if(keepalive_t < 0 && tx_timer == 0){
		#if DEBUG
			printf("keep alive sent.\n");
		#endif
			identifyclient();
			keepalive_t = KEEPALIVE_CYCLE;
		}
		if(tx_timer == 0) {
			keepalive_t--;
			usleep(50);	
		}		

		if(kbhit() && tx_timer == 0){
			getchar(); /* flush the buffer */
			if(commandmode()== 1)break;
		}
	} /* End of mainloop */

	send(fd_socket, &disconnect_packet, SIZE_COMMAND_PACKET, 0);	
	close(fd_socket);
	close(fd_serial);

	exit(0); 
}

<file_sep>/src/Makefile
SRC = irmc.c cwprotocol.c
OBJ = ${SRC:.c=.o}
LDFLAGS = -L/usr/local/lib -L/opt/local/lib  -lm -lmorse
CFLAGS = -I/usr/local/include -I/opt/local/include -Wall 
INSTALLDIR = ${HOME}/bin

all: options irmc 

options:
	@echo irmc build options:
	@echo "CFLAGS   = ${CFLAGS}"
	@echo "LDFLAGS  = ${LDFLAGS}"
	@echo "CC       = ${CC}"
	@echo "INSTALLDIR = ${INSTALLDIR}"

.c.o:
	@echo CC $<
	@${CC} -c ${CFLAGS} $<

irmc:   ${OBJ}
	@echo CC -o $@
	@${CC} -o $@ ${OBJ} ${LDFLAGS}

java:
	java -jar test/MorseKOB.jar 

clean:
	@echo cleaning
	@rm -f irmc irmc.core ${OBJ} 
install: irmc
	cp irmc ${INSTALLDIR}
<file_sep>/README.md
irmc - Internet Relay Morse Code
================================
IRMC stands for Internet Relay Morse Code and is an implementation of [MOIP](http://8ch9azbsfifz.github.io/moip/).

# How to build?
## Install dependency: morse keyer library
```
wget https://github.com/8cH9azbsFifZ/morse/archive/v0.1.tar.gz
tar xzf v0.1.tar.gz
cd morse-0.1
libtoolize
./autogen.sh
./configure  --with-portaudio
make
sudo make install
```

## Debian (Wheezy)
Some dependencies have to be installed:
```
apt-get install -y alsa-oss oss-compat build-essential autoconf libao-dev libtool
```
Afterwards compilation with `make` should work. If something went wrong, you may have
to adjust your `LD_LIBRARY_PATH`. Alternatively try:
```
LD_LIBRARY_PATH=/usr/local/lib ./irmc mtc-kob.dyndns.org 7890 33 123 
```

## OSX (Yosemite)
Compilation with make :)

For the USB serial devices you need a PL2303 driver 
(i.e. [PL2303_Serial-USB_on_OSX_Lion.pkg](http://changux.co/osx-installer-to-pl2303-serial-usb-on-osx-lio/)).

# Hardware interface options
A good description on how to build different interfaces (telegraph key, sounder or both) 
is given on the [MorseKOB Website](http://kob.sdf.org/morsekob/interface.htm). 
Landline telegraphs use "closed circuits" for communications; if you have built one at home, 
you may also use the [loop interface](http://kob.sdf.org/morsekob/docs/loopinterface.pdf).

Connection of a morse key:
[layout of pins](http://techpubs.sgi.com/library/dynaweb_docs/0650/SGI_Admin/books/MUX_IG/sgi_html/figures/4-2.serial.port.con.gif)

|  RS232    | DB9    | Function |   
| :-------- |:-------| :------  | 
|  DTR      | 4      | Manual Key / paddle common|
|  DSR      | 6      | Manual key / dot paddle|
|  CTS      | 8      | Dash paddle|
|  RTS      | 7      | Sounder output|
|  SG       | 5      | Sounder ground|


# Changelog
* v0.3 [zip](https://github.com/8cH9azbsFifZ/irmc/archive/v0.3.zip) - commandline option cleanup
* v0.2 [zip](https://github.com/8cH9azbsFifZ/irmc/archive/v0.2.zip) - ported to debian wheezy and osx yosemite, DG6FL
* v0.1 [zip](https://github.com/8cH9azbsFifZ/irmc/archive/v0.1.zip) - original version, VE7FEB

Code Quality
============
This is experimental code.
