/*
	MG485MST.C
	
	RS485 half duplex communication to another BL14xx/MicroG or BL15xx/MicroG2
	running mg485slv.c.

	The master can talk to up to 32 slaves (limited by hardware) with
	slave number ranging from 1 to 255. This master is only polling for slave
	no. 1.
	For other samples look into ..\samples\network.
*/

char rbuf[255];
char reply[40];
char message[40];

main()
{
int i, j;
int ercode;

	op_init_z1(8, rbuf, 0);
	// 8 for 9600 baud
	// rbuf for the receiver buffer
	// 0 for being the master
	
	j = 1;
	while(1)
	{
		hitwd();
		for(i = 0; i< 15000; i++) runwatch();
		hitwd();       // make sure we do not watchdog timeout
		sprintf(message, "Message # %d", j++);
		ercode = TalkToSlave( 1, message, strlen(message), 3, reply);
		if( ercode == 1)
		{
			printf("%s\n", reply);
		}
		else
		{
			printf("Link Failure or Bad Link\n");
		}
	}
}


// master talk send and receive data here
int TalkToSlave(int slave_no, char *query, int len, int ndelay, char *reply)
{

	int i;
	int ercode;

	ercode =  sendOp22( slave_no, query, len, ndelay);
	if( ercode == 1)
	{
		for( i = 0; i < rbuf[0] - 2; i++)
		{
			reply[i] = rbuf[1+i];
		}
		reply[i] = '\0';
	}
	return ercode;
}   


