/*
	CoboxQuery.java
	CoboxQuery

	Created by Tom Igoe on Tue Jun 22 2004.
  
	Searches for available Coboxes and XPorts by broadcasting the "Query of firmware version"
	command to port number 30718 (0x77FE). All available devices will respond with a 
	message containing firmware information and MAC address. 
	The IP address can be discovered from the returned message as well.
*/
import java.util.*;
import java.io.*;
import java.text.*;
import java.net.*;

public class CoboxQuery {
    DatagramPacket queryPacket;     // the packet we'll send
	int queryPort;					// port to send status query on
	InetAddress destinationIp;		// address to send to

	byte[] queryMsg;				// buffer for query msg
    DatagramSocket mySocket;		// the socket we'll open
	
    public CoboxQuery (DatagramSocket thisSocket) {
		queryPacket = null;			
		queryPort = 30718;			// port ot send status query on
		destinationIp = null;

		queryMsg = new byte[4];		// buffer for query msg
		mySocket = thisSocket;     // the socket we'll open
}


/*
	Sends a query packet
*/
	public void sendQuery(InetAddress destinationAddress) {
			destinationIp = destinationAddress;
			// format the query string:
			queryMsg[0] = 0x00;
			queryMsg[1] = 0x00;
			queryMsg[2] = 0x00;		
			queryMsg[3] = (byte)0xF6;

			System.out.println("Sending query to: " + destinationAddress.toString());
			queryPacket = new DatagramPacket(queryMsg, queryMsg.length, destinationIp, queryPort);
        
			// send the packet out the socket:
			try {
				mySocket.send(queryPacket);
			} catch (IOException expe) {System.out.println(expe);}
		}
	
	/*
          Takes the IP address xx.xx.xx.xx and returns xx.xx.xx.255:
	*/
  
	public InetAddress getBroadcastAddress (InetAddress thisAddress) {
		byte[] destination = new byte[4];
		InetAddress myAddress = null;
		destination[0] = thisAddress.getAddress()[0];
		destination[1] = thisAddress.getAddress()[1];
		destination[2] = thisAddress.getAddress()[2];
		destination[3] = (byte)0xFF;
		try {
			myAddress = InetAddress.getByAddress(destination);
		} catch (UnknownHostException uhe) {}
		return myAddress;
	}
}