package net.benhui.btgallery.l2cap_bt;

import java.io.*;
import javax.bluetooth.*;
import javax.microedition.io.*;

import net.benhui.btgallery.l2cap_gui.*;

/**
 *
 * <p>Title: Example L2CAP Client code</p>
 * <p>Description: Important area: send_SPP_message() </p>
 * This client only does the portion that send and receive data over a L2CAP
 * connection. In an actual client applicaion, you also need to do device
 * discovery and service discovery. This is taken care by Bluelet.
 * @author Ben Hui (www.benhui.net)
 * @version 1.0
 *
 * LICENSE:
 * This code is licensed under GPL. (See http://www.gnu.org/copyleft/gpl.html)
 */

public class L2CAP_Client
{

  public L2CAP_Client()
  {
  }


  /**
   * Send a message to server using L2CAP.
   * Connect to incoming service record, send a packet, and read
   * in a packet. This method illustrate how to send and receive
   * data using L2CAP.
   * Device and service discovery is part of L2CAP client but it is
   * done by Bluelet component. See L2CAP_MIDlet for usage of Bluelet.
   * @param msg
   */
  public void send_L2CAP_packet(ServiceRecord r, String msg)
  {

    // obtain the URL reference to this service on remote device
    String url  = r.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false );
    // add suggested MTU size. In this case, we pick 512 bytes.
    url += ";ReceiveMTU=512;TransmitMTU=512";
    log("url:"+url);

    try
    {
      // obtain connection and stream to this service
      L2CAPConnection con = (L2CAPConnection) Connector.open( url );
      log("connected to server, now reading...");
      int size = con.getTransmitMTU();
      log("TransmitMTU size "+size);
      // we send as much as TransmitMTU limited us
      byte[] data = new byte[size];
      // note: we assume msg is shorter than 512 bytes.
      // but for serious app, you should check the size of message and copy
      // only TransmitMTU size
      byte[] msg_data = msg.getBytes();
      System.arraycopy( msg_data, 0, data, 0, msg_data.length);

      con.send( data );
      log("sent "+size+" bytes to remote device");

      // this wait is artificial, the purpose to do wait until the
      // server side really receive the message before we close the connection
      // in theory, this is not necessary, but when I use the Rococo simulator,
      // sometimes the connection dropped on the server side when I close it here
      // it may be a bug in Rococo simulator.
      Thread.sleep(1000);

      // server should have echo the data back to us, read it here
      int read = con.receive( data );

      log("read in "+read+" bytes");

      // finish, close connection
      con.close();


    } catch (Exception e)
    {
      e.printStackTrace();
      L2CAP_MIDlet.alert( e, L2CAP_MIDlet.instance.l2cap_screen );
    }

  }

  public void log( String s )
  {
    L2CAP_MIDlet.log( s );
  }

}
