/*====================================================================*
 *
 *   int6kuart.c - Atheros Serial Line Device Manager;
 *
 *   This software and documentation is the property of Atheros 
 *   Corporation, Ocala, Florida. It is provided 'as is' without 
 *   expressed or implied warranty of any kind to anyone for any 
 *   reason. Atheros assumes no responsibility or liability for 
 *   errors or omissions in the software or documentation and 
 *   reserves the right to make changes without notification. 
 *   
 *   Atheros customers may modify and distribute the software 
 *   without obligation to Atheros. Since use of this software 
 *   is optional, users shall bear sole responsibility and 
 *   liability for any consequences of it's use. 
 *   
 *.  Atheros Powerline Toolkit for HomePlug AV;
 *:  Published 2006-2009 by Intellon Corp. ALL RIGHTS RESERVED;
 *;  For demonstration; Not for production use;
 *
 *   Contributor(s):
 *	Charles Maier <charles.maier@atheros.com>
 *
 *--------------------------------------------------------------------*/

#define _GETOPT_H

/*====================================================================*
 *   system header files;
 *--------------------------------------------------------------------*/

#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <net/ethernet.h>

#if defined (__linux__)
#	include <sys/io.h>
#	include <termios.h>
#elif defined (__APPLE__)
#	include <sys/io.h>
#	include <termios.h>
#elif defined (WIN32)
#else
#error "Unknown Environment"
#endif

/*====================================================================*
 *   custom header files;
 *--------------------------------------------------------------------*/

#include "../tools/getoptv.h"
#include "../tools/putoptv.h"
#include "../tools/version.h"
#include "../tools/number.h"
#include "../tools/memory.h"
#include "../tools/endian.h"
#include "../tools/files.h"
#include "../tools/flags.h"
#include "../tools/error.h"
#include "../tools/types.h"
#include "../int6k/problem.h"

/*====================================================================*
 *   custom source files;
 *--------------------------------------------------------------------*/

#ifndef MAKEFILE
#include "../tools/getoptv.c"
#include "../tools/putoptv.c"
#include "../tools/version.c"
#include "../tools/uintspec.c"
#include "../tools/basespec.c"
#include "../tools/synonym.c"
#include "../tools/todigit.c"
#include "../tools/error.c"
#include "../tools/checksum_32.c"
#include "../tools/hexencode.c"
#include "../tools/hexdump.c"
#include "../tools/hexstring.c"
#include "../tools/hexdecode.c"
#include "../tools/error.c"
#include "../tools/alert.c"
#endif

/*====================================================================*
 *   program constants;
 *--------------------------------------------------------------------*/

#define EXTRA 512
#define BLOCK 512
#define SERIALPORT "PLCUART"

#ifdef WIN32
#	define DEVICE "com1:"
#	define PAUSE(x) Sleep (1000 * (x))
#else
# 	define DEVICE "/dev/ttyUSB0"
#	define PAUSE(x) sleep (x);
#endif

#define UART_SILENCE 	(1 << 0)
#define UART_VERBOSE 	(1 << 1)
#define UART_COMMAND 	(1 << 2)
#define UART_WAKE 	(1 << 3)
#define UART_RESPOND 	(1 << 4)
#define UART_ATRV 	(1 << 5)
#define UART_ATRPM 	(1 << 6)
#define UART_ATSK1 	(1 << 7)
#define UART_ATSK2	(1 << 8)
#define UART_ATZ 	(1 << 9)
#define UART_ATDST1 	(1 << 10)
#define UART_ATDST2 	(1 << 11)
#define UART_ATNI 	(1 << 12)
#define UART_ATFD 	(1 << 13)
#define UART_ATPS 	(1 << 14)
#define UART_ATO 	(1 << 15)
#define UART_ATHSC 	(1 << 16)
#define UART_ATRP 	(1 << 17)
#define UART_ATWPF1 	(1 << 18)
#define UART_ATWPF2	(1 << 19)
#define UART_ATWNV 	(1 << 20)
#define UART_ATBSZ1 	(1 << 21)
#define UART_ATBSZ2	(1 << 22)
#define UART_ATTO 	(1 << 23)

/*====================================================================*
 *   program variables;
 *--------------------------------------------------------------------*/

typedef struct uart 

{
	struct _file_ port;
	struct _file_ pib;
	struct _file_ nvm;
	const char * command;
	char firmware [128];
	char pibversion [3];
	byte MAC [ETHER_ADDR_LEN];
	char NMK [16];
	char const * dstAddr;
	byte module;
	uint16_t bfsize;
	unsigned psTime;
	unsigned staIndex;
	uint16_t timeout;
	unsigned flags;
}

uart;

/*====================================================================*
 *
 *   struct command;
 *
 *   structure containing serial command buffer and two pointers; the
 *   buffer is used for both transmit and receive and shared by most
 *   function below; 
 * 
 *--------------------------------------------------------------------*/

static struct command 

{
	char buffer [EXTRA + BLOCK + BLOCK];
	signed length;
	signed offset;
}

command;

/*====================================================================*
 *
 *   void insert (char c);
 *
 *   insert a character into the command buffer at the current buffer
 *   position then increment the position pointer;
 *
 *   this function has direct access to the command buffer;
 *
 *--------------------------------------------------------------------*/

void insert (char c) 

{
	extern struct command command;
	if (command.length < sizeof (command.buffer)) 
	{
		command.buffer [command.length++] = c;
	}
	return;
}

/*====================================================================*
 *
 *   void string (char * string);
 *
 *   copy command buffer characters to external string; start a the
 *   current buffer position and continue until the buffer exhausts
 *   or a closing quote is encountered; terminate the string; 
 *
 *   this function has direct access to the command buffer;
 *
 *--------------------------------------------------------------------*/

void string (char * string) 

{
	extern struct command command;
	while ((command.offset < command.length) && (command.buffer [command.offset] != '\"')) 
	{
		*string++ = command.buffer [command.offset++];
	}
	*string = (char)(0);
	return;
}

/*====================================================================*
 *
 *   uint64_t hextoint (unsigned bytes);
 *
 *   this function has direct access to the command buffer;
 *
 *--------------------------------------------------------------------*/

uint64_t hextoint (unsigned bytes) 

{
	extern struct command command;
	uint64_t limit = -1;
	uint64_t value = 0;
	unsigned radix = 16;
	unsigned digit = 0;
	if (bytes < sizeof (limit)) 
	{
		limit <<= (bytes << 3);
		limit = ~limit;
	}
	while ((digit = todigit (command.buffer [command.offset])) < radix) 
	{
		value *= radix;
		value += digit;
		command.offset++;
		if (value > limit) 
		{
			command.buffer [command.offset] = (char)(0);
			error (1, EINVAL, "[%s] exceeds %d bits", command.buffer, (bytes << 3));
		}
	}
	return (value);
}

/*====================================================================*
 *
 *   void enhex (void const * memory, size_t extent);
 *   
 *   copy a memory region into command buffer at the current position
 *   and increment the buffer position pointer; convert bytes to hex 
 *   octets;
 *
 *   this function has direct access to the command buffer;
 *
 *--------------------------------------------------------------------*/

static void enhex (void const * memory, size_t extent) 

{
	extern struct command command;
	register byte * binary = (byte *)(memory);
	while ((command.length < sizeof (command.buffer)) && (extent--)) 
	{
		insert (DIGITS_HEX [(*binary >> 4) & 0x0F]);
		insert (DIGITS_HEX [(*binary >> 0) & 0x0F]);
		binary++;
	}
	return;
}

/*====================================================================*
 *
 *   void dehex (void * memory, size_t extent);
 *
 *   encode a memory region from the current command buffer position
 *   and increment the command buffer position pointer;
 *
 *   this function has direct access to the command buffer;
 *
 *--------------------------------------------------------------------*/

static void dehex (void * memory, size_t extent) 

{
	extern struct command command;
	register byte * binary = (byte *)(memory);
	unsigned digit;
	while ((command.offset < command.length) && (extent--)) 
	{
		*binary = 0;
		if ((digit = todigit (command.buffer [command.offset++])) > 0x0F) 
		{
			command.buffer [command.offset] = (char)(0);
			error (1, EINVAL, "[%s]1", command.buffer);
		}
		*binary |= digit << 4;
		if ((digit = todigit (command.buffer [command.offset++])) > 0x0F) 
		{
			command.buffer [command.offset] = (char)(0);
			error (1, EINVAL, "[%s]2", command.buffer);
		}
		*binary |= digit;
		binary++;
	}
	return;
}

/*====================================================================*
 *
 *   bool ischar ( char c);
 *
 *--------------------------------------------------------------------*/

bool ischar (char c) 

{
	extern struct command command;
	if (command.offset >= command.length) 
	{
		return (false);
	}
	if (command.buffer [command.offset++] != (c)) 
	{
		return (false);
	}
	return (true);
}

/*====================================================================*
 *
 *   void mustbe (char c);
 *
 *   test current buffer character; terminate program on error;
 *
 *   this function has direct access to the command buffer;
 *
 *--------------------------------------------------------------------*/

static void mustbe (char c) 

{
	extern struct command command;
	if (command.offset >= command.length) 
	{
		command.buffer [command.offset] = (char)(0);
		error (1, EINVAL, "[%s]: overflow", command.buffer);
	}
	if (command.buffer [command.offset++] != (c)) 
	{
		command.buffer [command.offset] = (char)(0);
		error (1, EINVAL, "[%s]: expecting 0x%02X", command.buffer, c);
	}
	return;
}

/*====================================================================*
 *
 *   void finish ();
 *
 *--------------------------------------------------------------------*/

void finish () 

{
	extern struct command command;
	memset (&command, 0, sizeof (command));
	return;
}

/*====================================================================*
 *
 *   void sendcommand (struct uart * uart);
 *
 *   terminate command buffer with a NUL byte for printf purposes'\0', echo the command 
 *   i
 *   then send the command;
 *
 *   this function has direct access to the command buffer;
 *
 *--------------------------------------------------------------------*/

static void sendcommand (struct uart * uart) 

{
	extern struct command command;
	if (_anyset (uart->flags, UART_VERBOSE)) 
	{
		write (STDERR_FILENO, command.buffer, command.length);
		write (STDERR_FILENO, "\n", sizeof (char));
	}
	if (write (uart->port.file, command.buffer, command.length) < command.length) 
	{
		error (1, errno, "Can't write to %d %s", uart->port.file, uart->port.name);
	}
	command.offset = 0;
	command.length = 0;
	return;
}

/*====================================================================*
 *
 *   void readcommand (struct uart * uart);
 *
 *   read response serial line and log the response;
 *
 *   this function has direct access to the command buffer;
 *
 *--------------------------------------------------------------------*/

static void readcommand (struct uart * uart) 

{
	extern struct command command;
#if defined (WIN32)
	Sleep (250);
#else
	usleep (250000);
#endif
	memset (&command, 0, sizeof (command));
	command.length = read (uart->port.file, command.buffer, sizeof (command.buffer));
	if (command.length < 0) 
	{
		error (1, errno, "Bad response from %s", uart->port.name);
	}
	if (command.length == 0) 
	{
		error (1, errno, "No response from %s", uart->port.name);
	}
	if (_anyset (uart->flags, UART_VERBOSE)) 
	{
		write (STDERR_FILENO, command.buffer, command.length);
		write (STDERR_FILENO, "\n", sizeof (char));
	}
	if (!memcmp (command.buffer, "ERROR", 5))
	{
		error (1, ECANCELED, "Device refused request");
	}
	return;
}

/*====================================================================*
 *
 *   void at_writenvm (struct uart * uart);
 *
 *   write entire nvm file using the firmware image command "ATWPF";
 *
 *   this function has direct access to the command buffer;
 *
 *--------------------------------------------------------------------*/

static void at_writenvm (struct uart * uart) 

{
	extern struct command command;
	byte memory [BLOCK];
	signed mblock = sizeof (memory);
	uint16_t mlength = 0;
	uint32_t moffset = 0;
	uint16_t olength = 0;
	uint32_t ooffset = 0;
	uint32_t ochksum;
	uint32_t mchksum;
	while ((mblock = read (uart->nvm.file, memory, mblock)) > 0) 
	{
		insert ('i');
		insert ('T');
		insert ('W');
		insert ('P');
		insert ('F');
		insert ('1');
		insert (',');
		mchksum = checksum_32 (memory, (size_t)(mblock), 0);
		mlength = (uint16_t)(mblock);
		mlength = HTOBE16 (mlength);
		enhex (&mlength, sizeof (mlength));
		mlength = BE16TOH (mlength);
		insert (',');
		moffset = HTOBE32 (moffset);
		enhex (&moffset, sizeof (moffset));
		moffset = BE32TOH (moffset);
		insert (',');
		mchksum = HTOBE32 (mchksum);
		enhex (&mchksum, sizeof (mchksum));
		mchksum = BE32TOH (mchksum);
		insert (',');
		enhex (memory, mlength);
		insert ('\r');
		sendcommand (uart);
		readcommand (uart);
		mustbe ('O');
		mustbe ('K');
		if (!ischar ('1')) 
		{
			command.buffer [command.offset] = (char)(0);
			error (1, EINVAL, "[%s]: expected module 1", command.buffer);
		}
		mustbe (',');
		olength = (uint16_t)(hextoint (sizeof (olength)));
		if (olength != mlength) 
		{
			command.buffer [command.offset] = (char)(0);
			error (1, EINVAL, "[%s]: expected length %X", command.buffer, mlength);
		}
		mustbe (',');
		ooffset = (uint32_t)(hextoint (sizeof (ooffset)));
		if (ooffset != moffset) 
		{
			command.buffer [command.offset] = (char)(0);
			error (1, EINVAL, "[%s]: expected offset %X", command.buffer, moffset);
		}
		mustbe (',');
		ochksum = (uint32_t)(hextoint (sizeof (ochksum)));
		if (ochksum != mchksum) 
		{
			command.buffer [command.offset] = (char)(0);
			error (1, EINVAL, "[%s]: expected checksum %X (%X)", command.buffer, mchksum, ochksum);
		}
		mustbe (',');
		dehex (memory, mblock);
		mustbe ('\r');
		finish ();
		moffset += mlength;
		if (_allclr (uart->flags, (UART_VERBOSE | UART_SILENCE)))
		{
			write (STDOUT_FILENO, ".", 1);
		}
	}
#ifndef WIN32	
	if (_allclr (uart->flags, (UART_VERBOSE | UART_SILENCE)))
	{
		write (STDOUT_FILENO, "\n", 1);
	}
#endif
	return;
}

/*====================================================================*
 *
 *   void at_writepib (struct uart * uart);
 *
 *   write entire pib file using the firmware image command "ATWPF";
 *
 *   this function has direct access to the command buffer;
 *
 *--------------------------------------------------------------------*/

static void at_writepib (struct uart * uart) 

{
	extern struct command command;
	byte memory [BLOCK];
	signed mblock = sizeof (memory);
	uint16_t mlength = 0;
	uint16_t moffset = 0;
	uint32_t mchksum;
	uint16_t olength = 0;
	uint16_t ooffset = 0;
	uint32_t ochksum;
	while ((mblock = read (uart->pib.file, memory, mblock)) > 0) 
	{
		insert ('A');
		insert ('T');
		insert ('W');
		insert ('P');
		insert ('F');
		insert ('2');
		insert (',');
		mchksum = checksum_32 (memory, (size_t)(mblock), 0);
		mlength = (uint16_t)(mblock);
		mlength = HTOBE16 (mlength);
		enhex (&mlength, sizeof (mlength));
		mlength = BE16TOH (mlength);
		insert (',');
		moffset = HTOBE16 (moffset);
		enhex (&moffset, sizeof (moffset));
		moffset = BE16TOH (moffset);
		insert (',');
		mchksum = HTOBE32 (mchksum);
		enhex (&mchksum, sizeof (mchksum));
		mchksum = BE32TOH (mchksum);
		insert (',');
		enhex (memory, mlength);
		insert ('\r');
		sendcommand (uart);
		readcommand (uart);
		mustbe ('O');
		mustbe ('K');
		if (!ischar ('2')) 
		{
			command.buffer [command.offset] = (char)(0);
			error (1, EINVAL, "[%s]: expected module 2", command.buffer);
		}
		mustbe (',');
		olength = (uint16_t)(hextoint (sizeof (olength)));
		if (olength != mlength) 
		{
			command.buffer [command.offset] = (char)(0);
			error (1, EINVAL, "[%s]: expected length %X", command.buffer, mlength);
		}
		mustbe (',');
		ooffset = (uint16_t)(hextoint (sizeof (ooffset)));
		if (ooffset != moffset) 
		{
			command.buffer [command.offset] = (char)(0);
			error (1, EINVAL, "[%s]: expected offset %X", command.buffer, moffset);
		}
		mustbe (',');
		ochksum = (uint32_t)(hextoint (sizeof (ochksum)));
		if (ochksum != mchksum) 
		{
			command.buffer [command.offset] = (char)(0);
			error (1, EINVAL, "[%s]: expected checksum %X (%X)", command.buffer, mchksum, ochksum);
		}
		mustbe (',');
		dehex (memory, mblock);
		mustbe ('\r');
		finish ();
		moffset += mlength;
		if (_allclr (uart->flags, (UART_VERBOSE | UART_SILENCE)))
		{
			write (STDOUT_FILENO, ".", 1);
		}
	}
#ifndef WIN32
	if (_allclr (uart->flags, (UART_VERBOSE | UART_SILENCE)))
	{
		write (STDOUT_FILENO, "\n", 1);
	}
#endif
	return;
}

/*====================================================================*
 *
 *   void at_readpib (struct uart * uart);
 *
 *   read PIB command "ATRP";
 *
 *   this function has direct access to the command buffer;
 *
 *--------------------------------------------------------------------*/

static void at_readpib (struct uart * uart) 

{
	extern struct command command;
	static byte memory [BLOCK];
	signed mblock = sizeof (memory);
	uint16_t mextent = 0;
	uint16_t mlength = 0;
	uint16_t moffset = 0;
	uint16_t olength = 0;
	uint16_t ooffset = 0;
	insert ('A');
	insert ('T');
	insert ('R');
	insert ('P');
	insert ('2');
	insert (',');
	insert ('4');
	insert ('\r');
	sendcommand (uart);
	readcommand (uart);
	mustbe ('O');
	mustbe ('K');
	mustbe ('2');
	mustbe (',');
	mustbe ('4');
	mustbe (',');
	dehex (&mextent, sizeof (mextent));
	mextent = LE16TOH (mextent);
	mustbe ('\r');
	finish ();
	while (mextent) 
	{
		insert ('A');
		insert ('T');
		insert ('R');
		insert ('P');
		if (mblock > mextent) 
		{
			mblock = mextent;
		}
		mlength = (uint16_t)(mblock);
		mlength = HTOBE16 (mlength);
		enhex (&mlength, sizeof (mlength));
		mlength = BE16TOH (mlength);
		insert (',');
		moffset = HTOBE16 (moffset);
		enhex (&moffset, sizeof (moffset));
		moffset = BE16TOH (moffset);
		insert ('\r');
		sendcommand (uart);
		readcommand (uart);
		mustbe ('O');
		mustbe ('K');
		olength = (uint16_t)(hextoint (sizeof (olength)));
		if (olength != mlength) 
		{
			command.buffer [command.offset] = (char)(0);
			error (1, EINVAL, "[%s]: have %d bytes but wanted %d", command.buffer, olength, mlength);
		}
		mustbe (',');
		ooffset = (uint16_t)(hextoint (sizeof (ooffset)));
		if (ooffset != moffset) 
		{
			command.buffer [command.offset] = (char)(0);
			error (1, EINVAL, "[%s]: expected offset %X", command.buffer, moffset);
		}
		mustbe (',');
		dehex (memory, mblock);
		if (write (uart->pib.file, memory, mblock) < mblock) 
		{
			command.buffer [command.offset] = (char)(0);
			error (1, errno, "[%s]: expected length %d", command.buffer, mblock);
		}
		mustbe ('\r');
		finish ();
		moffset += mblock;
		mextent -= mblock;
		if (_allclr (uart->flags, (UART_VERBOSE | UART_SILENCE)))
		{
			write (STDOUT_FILENO, ".", 1);
		}
	}
#ifndef WIN32
	if (_allclr (uart->flags, (UART_VERBOSE | UART_SILENCE)))
	{
		write (STDOUT_FILENO, "\n", 1);
	}
#endif
	return;
}

/*====================================================================*
 *
 *   void at_wake (struct uart * uart);
 *
 *   send wake command "+++" to enter command mode; 
 *
 *--------------------------------------------------------------------*/

static void at_wake (struct uart * uart) 

{
	insert ('+');
	insert ('+');
	insert ('+');
	sendcommand (uart);
	readcommand (uart);
	mustbe ('O');
	mustbe ('K');
	mustbe ('\r');
	finish ();
	return;
}

/*====================================================================*
 *
 *   void at_command (struct uart * uart);
 *
 *--------------------------------------------------------------------*/

static void at_command (struct uart * uart) 

{
	while (*uart->command) 
	{
		insert (*uart->command++);
	}
	insert ('\r');
	sendcommand (uart);
	readcommand (uart);
	finish ();
	return;
}

/*====================================================================*
 *
 *   void at_respond (struct uart * uart);
 *
 *   send test command "AT";    
 *
 *--------------------------------------------------------------------*/

static void at_respond (struct uart * uart) 

{
	insert ('A');
	insert ('T');
	insert ('\r');
	sendcommand (uart);
	readcommand (uart);
	mustbe ('O');
	mustbe ('K');
	mustbe ('\r');
	finish ();
	return;
}

/*====================================================================*
 *
 *   void atz (struct uart * uart);
 *
 *   send reset command "ATZ"; no response is expected;
 *
 *--------------------------------------------------------------------*/

static void atz (struct uart * uart) 

{
	insert ('A');
	insert ('T');
	insert ('Z');
	insert ('\r');
	sendcommand (uart);
	finish ();
	return;
}

/*====================================================================*
 *
 *   void atrv (struct uart * uart);
 *
 *   send command "ATRV";
 *
 *--------------------------------------------------------------------*/

static void atrv (struct uart * uart) 

{
	insert ('A');
	insert ('T');
	insert ('R');
	insert ('V');
	insert ('\r');
	sendcommand (uart);
	readcommand (uart);
	mustbe ('O');
	mustbe ('K');
	mustbe ('\"');
	string (uart->firmware);
	mustbe ('\"');
	mustbe ('\r');
	finish ();
	printf ("%s\n", uart->firmware);
	return;
}

/*====================================================================*
 *
 *   void atrpm (struct uart * uart);
 *
 *   read and display network identity using command "ATRPM";
 *
 *--------------------------------------------------------------------*/

static void atrpm (struct uart * uart) 

{
	char buffer [ETHER_ADDR_LEN * 3];
	insert ('A');
	insert ('T');
	insert ('R');
	insert ('P');
	insert ('M');
	insert ('\r');
	sendcommand (uart);
	readcommand (uart);
	mustbe ('O');
	mustbe ('K');
	mustbe ('\"');
	string (uart->pibversion);
	mustbe ('\"');
	mustbe (',');
	dehex (uart->MAC, sizeof (uart->MAC));
	mustbe ('\r');
	finish ();
	printf ("%s %s\n", uart->pibversion, hexstring (buffer, sizeof (buffer), uart->MAC, sizeof (uart->MAC)));
	return;
}

/*====================================================================*
 *
 *   void atsk1 (struct uart * uart);
 *
 *   send Set Key command "ATSK"; ask device for NMK; encode returned
 *   key into uart-NMK;
 *
 *--------------------------------------------------------------------*/

static void atsk1 (struct uart * uart) 

{
	char buffer [48];
	insert ('A');
	insert ('T');
	insert ('S');
	insert ('K');
	insert ('?');
	insert ('\r');
	sendcommand (uart);
	readcommand (uart);
	mustbe ('O');
	mustbe ('K');
	dehex (uart->NMK, sizeof (uart->NMK));
	mustbe ('\r');
	finish ();
	printf ("%s\n", hexstring (buffer, sizeof (buffer), uart->NMK, sizeof (uart->NMK)));
	return;
}

/*====================================================================*
 *
 *   void atsk2 (struct uart * uart);
 *
 *   send Set Key command "ATSK"; send device the NMK; encode returned 
 *
 *--------------------------------------------------------------------*/

static void atsk2 (struct uart * uart) 

{
	char buffer [48];
	insert ('A');
	insert ('T');
	insert ('S');
	insert ('K');
	enhex (uart->NMK, sizeof (uart->NMK));
	insert ('\r');
	sendcommand (uart);
	readcommand (uart);
	mustbe ('O');
	mustbe ('K');
	dehex (uart->NMK, sizeof (uart->NMK));
	mustbe ('\r');
	finish ();
	printf ("%s\n", hexstring (buffer, sizeof (buffer), uart->NMK, sizeof (uart->NMK)));
	return;
}

/*====================================================================*
 *
 *   void atdst1 (struct uart * uart);
 *
 *   read transparent mode destination MAC address command "ATDST?";
 *
 *--------------------------------------------------------------------*/

static void atdst1 (struct uart * uart) 

{
	char buffer [ETHER_ADDR_LEN * 3];
	insert ('A');
	insert ('T');
	insert ('D');
	insert ('S');
	insert ('T');
	insert ('?');
	insert ('\r');
	sendcommand (uart);
	readcommand (uart);
	mustbe ('O');
	mustbe ('K');
	dehex (uart->MAC, sizeof (uart->MAC));
	mustbe ('\r');
	finish ();
	printf ("%s\n", hexstring (buffer, sizeof (buffer), uart->MAC, sizeof (uart->MAC)));
	return;
}

/*====================================================================*
 *
 *   void atdst2 (struct uart * uart);
 *
 *   read transparent mode destination MAC address command "ATDST?";
 *
 *--------------------------------------------------------------------*/

static void atdst2 (struct uart * uart) 

{
	char buffer [ETHER_ADDR_LEN * 3];
	insert ('A');
	insert ('T');
	insert ('D');
	insert ('S');
	insert ('T');
	enhex (uart->MAC, sizeof (uart->MAC));
	insert ('\r');
	sendcommand (uart);
	readcommand (uart);
	mustbe ('O');
	mustbe ('K');
	dehex (uart->MAC, sizeof (uart->MAC));
	mustbe ('\r');
	finish ();
	printf ("%s\n", hexstring (buffer, sizeof (buffer), uart->MAC, sizeof (uart->MAC)));
	return;
}

/*====================================================================*
 *
 *   void atni (struct uart * uart);
 *
 *   reset device to factory default pib command "ATNI";
 *
 *--------------------------------------------------------------------*/

static void atni (struct uart * uart) 

{
	insert ('A');
	insert ('T');
	insert ('N');
	insert ('I');
	insert ('?');
	insert ('\r');
	sendcommand (uart);
	readcommand (uart);
	mustbe ('O');
	mustbe ('K');
	mustbe ('\r');
	finish ();
	return;
}

/*====================================================================*
 *
 *   void atfd (struct uart * uart);
 *
 *   reset device to factory default pib command "ATFD";
 *
 *--------------------------------------------------------------------*/

static void atfd (struct uart * uart) 

{
	insert ('A');
	insert ('T');
	insert ('F');
	insert ('D');
	insert ('\r');
	sendcommand (uart);
	readcommand (uart);
	mustbe ('O');
	mustbe ('K');
	mustbe ('\r');
	finish ();
	return;
}

/*====================================================================*
 *
 *   void atps (struct uart * uart);
 *
 *   etner power save mode command "ATPS";
 *
 *--------------------------------------------------------------------*/

static void atps (struct uart * uart) 

{
	uint16_t time = 0;
	uint16_t otime = 0;
	insert ('A');
	insert ('T');
	insert ('P');
	insert ('S');
	enhex (&time, sizeof (time));
	insert ('\r');
	sendcommand (uart);
	readcommand (uart);
	mustbe ('O');
	mustbe ('K');
	otime = (uint16_t)(hextoint (sizeof (otime)));
	mustbe ('\r');
	finish ();
	return;
}

/*====================================================================*
 *
 *   void ato (struct uart * uart);
 *
 *   exit command mode and enter tyransparent mode command "ATO";
 *
 *--------------------------------------------------------------------*/

static void ato (struct uart * uart) 

{
	insert ('A');
	insert ('T');
	insert ('O');
	insert ('\r');
	sendcommand (uart);
	readcommand (uart);
	mustbe ('O');
	mustbe ('K');
	mustbe ('\r');
	finish ();
	return;
}

/*====================================================================*
 *
 *   void athsc (struct uart * uart);
 *
 *   exit command mode; enter high speed command mode "ATHSC";
 *
 *--------------------------------------------------------------------*/

static void athsc (struct uart * uart) 

{
	insert ('A');
	insert ('T');
	insert ('H');
	insert ('S');
	insert ('C');
	insert ('\r');
	sendcommand (uart);
	readcommand (uart);
	mustbe ('O');
	mustbe ('K');
	mustbe ('\r');
	finish ();
	return;
}

/*====================================================================*
 *
 *   void atwnv (struct uart * uart);
 *
 *   write PIB and/or firmware to NVM "ATWNVx";
 *
 *--------------------------------------------------------------------*/

static void atwnv (struct uart * uart) 

{
	byte omodule;
	insert ('A');
	insert ('T');
	insert ('W');
	insert ('N');
	insert ('V');
	enhex (&uart->module, sizeof (uart->module));
	insert ('\r');
	sendcommand (uart);
	readcommand (uart);
	mustbe ('O');
	mustbe ('K');
	omodule = (byte)(hextoint (sizeof (omodule)));
	if (omodule != uart->module) 
	{
		error (1, EINVAL, "[%s]: expected module %d", command.buffer, uart->module);
	}
	mustbe ('\r');
	finish ();
	return;
}

/*====================================================================*
 *
 *   void atbsz1 (struct uart * uart);
 *
 *   get transparent mode buffer size "ATBSZ?";
 *
 *--------------------------------------------------------------------*/

static void atbsz1 (struct uart * uart) 

{
	insert ('A');
	insert ('T');
	insert ('B');
	insert ('S');
	insert ('Z');
	insert ('?');
	insert ('\r');
	sendcommand (uart);
	readcommand (uart);
	mustbe ('O');
	mustbe ('K');
	uart->bfsize = (uint16_t)(hextoint (sizeof (uart->bfsize)));
	mustbe ('\r');
	finish ();
	printf ("%d\n", uart->bfsize);
	return;
}

/*====================================================================*
 *
 *   void atbsz2 (struct uart * uart);
 *
 *   set transparent mode buffer size "ATBSZn";
 *
 *--------------------------------------------------------------------*/

static void atbsz2 (struct uart * uart) 

{
	uint16_t obfsize;
	insert ('A');
	insert ('T');
	insert ('B');
	insert ('S');
	insert ('Z');
	uart->bfsize = HTOBE16 (uart->bfsize);
	enhex (&uart->bfsize, sizeof (uart->bfsize));
	uart->bfsize = BE16TOH (uart->bfsize);
	insert ('\r');
	sendcommand (uart);
	readcommand (uart);
	mustbe ('O');
	mustbe ('K');
	obfsize = (uint16_t)(hextoint (sizeof (obfsize)));
	if (obfsize != uart->bfsize) 
	{
		error (1, EINVAL, "[%s]: expected buffer size %04X", command.buffer, uart->bfsize);
	}
	mustbe ('\r');
	finish ();
	printf ("%d\n", uart->bfsize);
	return;
}

/*====================================================================*
 *
 *   void atto (struct uart * uart);
 *
 *   set transparent mode buffer timeout "ATTO";
 *
 *--------------------------------------------------------------------*/

static void atto (struct uart * uart) 

{
	uint16_t otimeout;
	insert ('A');
	insert ('T');
	insert ('T');
	insert ('O');
	uart->timeout = HTOBE16 (uart->timeout);
	enhex (&uart->timeout, sizeof (uart->timeout));
	uart->timeout = BE16TOH (uart->timeout);
	insert ('\r');
	sendcommand (uart);
	readcommand (uart);
	mustbe ('O');
	mustbe ('K');
	otimeout = (uint16_t)(hextoint (sizeof (otimeout)));
	if (otimeout != uart->timeout) 
	{
		error (1, EINVAL, "[%s]: expected timeout %04X", command.buffer, uart->timeout);
	}
	mustbe ('\r');
	finish ();
	return;
}

/*====================================================================*
 *
 *   void manager (struct uart * uart);
 *
 *   examine flagword in struct uart and perform requested operations
 *   in the order that bits are tested; the order that bits are tested
 *   may be changed as needed;
 *
 *--------------------------------------------------------------------*/

static void manager (struct uart * uart) 

{
	if (_anyset (uart->flags, UART_WAKE)) 
	{
		at_wake (uart);
	}
	if (_anyset (uart->flags, UART_COMMAND)) 
	{
		at_command (uart);
	}
	if (_anyset (uart->flags, UART_RESPOND)) 
	{
		at_respond (uart);
	}
	if (_anyset (uart->flags, UART_ATRV)) 
	{
		atrv (uart);
	}
	if (_anyset (uart->flags, UART_ATRPM)) 
	{
		atrpm (uart);
	}
	if (_anyset (uart->flags, UART_ATDST1)) 
	{
		atdst1 (uart);
	}
	if (_anyset (uart->flags, UART_ATDST2)) 
	{
		atdst2 (uart);
	}
	if (_anyset (uart->flags, UART_ATZ)) 
	{
		atz (uart);
	}
	if (_anyset (uart->flags, UART_ATFD)) 
	{
		atfd (uart);
	}
	if (_anyset (uart->flags, UART_ATPS)) 
	{
		atps (uart);
	}
	if (_anyset (uart->flags, UART_ATO)) 
	{
		ato (uart);
	}
	if (_anyset (uart->flags, UART_ATNI)) 
	{
		atni (uart);
	}
	if (_anyset (uart->flags, UART_ATHSC)) 
	{
		athsc (uart);
	}
	if (_anyset (uart->flags, UART_ATSK1)) 
	{
		atsk1 (uart);
	}
	if (_anyset (uart->flags, UART_ATSK2)) 
	{
		atsk2 (uart);
	}
	if (_anyset (uart->flags, UART_ATRP)) 
	{
		at_readpib (uart);
	}
	if (_anyset (uart->flags, UART_ATWPF1)) 
	{
		at_writenvm (uart);
	}
	if (_anyset (uart->flags, UART_ATWPF2)) 
	{
		at_writepib (uart);
	}
	if (_anyset (uart->flags, UART_ATWNV)) 
	{
		atwnv (uart);
	}
	if (_anyset (uart->flags, UART_ATBSZ1)) 
	{
		atbsz1 (uart);
	}
	if (_anyset (uart->flags, UART_ATBSZ2)) 
	{
		atbsz2 (uart);
	}
	if (_anyset (uart->flags, UART_ATTO)) 
	{
		atto (uart);
	}
	return;
}

/*====================================================================*
 *
 *   int main (int argc, const char * argv []);
 *
 *
 *
 *.  Atheros Powerline Toolkit for HomePlug AV;
 *:  Published 2006-2009 by Intellon Corp. ALL RIGHTS RESERVED;
 *;  For demonstration; Not for production use;
 *
 *--------------------------------------------------------------------*/

int main (int argc, const char * argv []) 

{
	static const char *optv [] = 
	{
		"bB:c:C:dD:HImM:n:N:Op:P:qrRs:tTvwW:",
		"",
		"Atheros Serial Line Device Manager",
		"b\tget Transparent Mode buffer size [ATBSZ?]",
		"B n\tset Transparent Mode buffer size [ATBSZn]",
		"c s\tsend custom serial line command (s)",
		"C x\tcommit module (x) to NVM [ATWNVx]",
		"d\tget destination mac address [ATDST?]",
		"D x\tset destination mac address [ATDSTx]",
		"H\tplace device in High Speed Command Mode [ATHSC]",
		"I\tget PIB version and MAC address [ATRPM]",
		"m\tget network membership key [ATSK?]",
		"M x\tset network membership key [ATSKx]",
		"N f\twrite NVM file (f) to SDRAM [ATWFP1]",
		"O\tplace device in Transparent Mode [ATO]",
		"p f\tread PIB from SDRAM to file (f) [ATRP]",
		"P f\twrite PIB file (f) to SDRAM [ATWFP2]",
		"q\tplace program in quiet mode",
		"r\tget hardware/firmware revision [ATRV]",
		"R\treset device [ATZ]",
		"s f\tserial port is (f) [" DEVICE "]",
		"S\tenter power save mode [ATPS]",
		"t\ttest device [AT]",
		"T\treset to factory defaults [ATFD]",
		"v\tplace program verbose mode",
		"w\tplace device in Command Mode [+++]",
		"W x\tset Transparent Mode aggregation timeout [ATTO]",
		(const char *) (0) 
	};
	struct uart uart = 
	{
		{
			0,
			DEVICE 
		},
		{
			-1,
			"nvmfile" 
		},
		{
			-1,
			"pibfile" 
		}
	};

#if defined (WIN32)

	HANDLE hSerial;
	DCB dcbSerial = 
	{
		0 
	};
	COMMTIMEOUTS timeouts;

#elif defined (__linux__)

	struct termios termios;

#else
#error "Unknown environment"
#endif

	signed c;
	if (getenv (SERIALPORT)) 
	{
		uart.port.name = strdup (getenv (SERIALPORT));
	}
	while ((c = getoptv (argc, argv, optv)) != -1) 
	{
		switch (c) 
		{
		case 'b':
			_setbits (uart.flags, UART_ATBSZ1);
			break;
		case 'B':
			_setbits (uart.flags, UART_ATBSZ2);
			uart.bfsize = (uint16_t)(uintspec (optarg, 1, 1500));
			break;
		case 'c':
			_setbits (uart.flags, UART_COMMAND);
			uart.command = optarg;
			break;
		case 'C':
			_setbits (uart.flags, UART_ATWNV);
			uart.module = (byte)(basespec (optarg, 16, sizeof (uart.module)));
			break;
		case 'd':
			_setbits (uart.flags, UART_ATDST1);
			break;
		case 'D':
			_setbits (uart.flags, UART_ATDST2);
			if (!hexencode (uart.MAC, sizeof (uart.MAC), optarg)) 
			{
				error (1, EINVAL, INT6K_BAD_MAC, optarg);
			}
			break;
		case 'H':
			_setbits (uart.flags, UART_ATHSC);
			break;
		case 'I':
			_setbits (uart.flags, UART_ATRPM);
			break;
		case 'm':
			_setbits (uart.flags, UART_ATSK1);
			break;
		case 'M':
			_setbits (uart.flags, UART_ATSK2);
			if (!hexencode (uart.NMK, sizeof (uart.NMK), optarg)) 
			{
				error (1, EINVAL, INT6K_BAD_NMK, optarg);
			}
			break;
		case 'N':
			uart.nvm.name = optarg;
			if ((uart.nvm.file = open (uart.nvm.name, O_BINARY | O_RDONLY)) == -1) 
			{
				error (1, errno, "%s", uart.nvm.name);
			}
			_setbits (uart.flags, UART_ATWPF1);
			break;
		case 'O':
			_setbits (uart.flags, UART_ATO);
			break;
		case 'P':
			uart.pib.name = optarg;
			if ((uart.pib.file = open (uart.pib.name, O_BINARY | O_RDONLY)) == -1) 
			{
				error (1, errno, "%s", uart.pib.name);
			}
			_setbits (uart.flags, UART_ATWPF2);
			break;
		case 'p':
			uart.pib.name = optarg;
			if ((uart.pib.file = open (uart.pib.name, O_BINARY|O_CREAT|O_RDWR|O_TRUNC, FILE_FILEMODE)) == -1) 
			{
				error (1, errno, "%s", uart.pib.name);
			}

#ifndef WIN32

			chown (optarg, getuid (), getgid ());

#endif

			_setbits (uart.flags, UART_ATRP);
			break;
		case 'q':
			_setbits (uart.flags, UART_SILENCE);
			break;
		case 'r':
			_setbits (uart.flags, UART_ATRV);
			break;
		case 'R':
			_setbits (uart.flags, UART_ATZ);
			break;
		case 'S':
			_setbits (uart.flags, UART_ATPS);
			break;
		case 's':
			uart.port.name = optarg;
			break;
		case 'T':
			_setbits (uart.flags, UART_ATFD);
			break;
		case 't':
			_setbits (uart.flags, UART_RESPOND);
			break;
		case 'v':
			_setbits (uart.flags, UART_VERBOSE);
			break;
		case 'w':
			_setbits (uart.flags, UART_WAKE);
			break;
		case 'W':
			_setbits (uart.flags, UART_ATTO);
			uart.timeout = (unsigned)(uintspec (optarg, 1, 2000));
			break;
		default:
			break;
		}
	}
	argc -= optind;
	argv += optind;
	if (argc) 
	{
		putoptv (optv);
		return (1);
	}
	if (_anyset (uart.flags, UART_VERBOSE)) 
	{
		alert ("using %s", uart.port.name);
	}

#if defined (WIN32)

	hSerial = CreateFile (uart.port.name, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
	if (hSerial == INVALID_HANDLE_VALUE) 
	{
		error (1, 0, "Can't open %s", uart.port.name);
	}
	dcbSerial.DCBlength = sizeof (dcbSerial);
	if (!GetCommState (hSerial, &dcbSerial)) 
	{
		error (1, 0, "Can't read %s state", uart.port.name);
	}
	dcbSerial.BaudRate = CBR_115200;
	dcbSerial.ByteSize = 8;
	dcbSerial.StopBits = ONESTOPBIT;
	dcbSerial.Parity = NOPARITY;
	if (!SetCommState (hSerial, &dcbSerial)) 
	{
		error (1, 0, "Can't save %s state", uart.port.name);
	}
	timeouts.ReadIntervalTimeout = 10;
	timeouts.ReadTotalTimeoutConstant = 50;
	timeouts.ReadTotalTimeoutMultiplier = 10;
	timeouts.WriteTotalTimeoutConstant = 50;
	timeouts.WriteTotalTimeoutMultiplier = 10;
	if (!SetCommTimeouts(hSerial, &timeouts)) 
	{
		error (1, 0, "Can't set %s timeouts", uart.port.name);
	}
	CloseHandle (hSerial);
	if ((uart.port.file = open (uart.port.name, O_BINARY|O_RDWR)) == -1) 
	{
		error (1, errno, "Can't open %s", uart.port.name);
	}

#elif defined (__linux__)

	if ((uart.port.file = open (uart.port.name, O_BINARY|O_RDWR)) == -1) 
	{
		error (1, errno, "Can't open %s", uart.port.name);
	}
	tcgetattr (uart.port.file, &termios);
	cfmakeraw (&termios);
	termios.c_cflag |= CS8;
	cfsetospeed (&termios, B115200);
	tcsetattr (uart.port.file, TCSANOW, &termios);

#else
#error "Unknown environment"
#endif

	manager (&uart);
	close (uart.port.file);
	exit (0);
}