26.6 Creating an IrDA Client

 <  Day Day Up  >  

You want to create an Infrared Data Association (IrDA) client application that can communicate using infrared communication with a server.


Technique

The .NET Compact Framework contains the ability to communicate with other devices using an infrared (IR) connection, something the full .NET Framework doesn't have without resorting to pure Socket communications. This recipe and the next look at the process to both send and receive data using an infrared port on a mobile device. Additionally, we explain an IR chat application to demonstrate the concepts, and we use the terms client and server even though we create only one application. In the traditional sense of the words, a client is the portion that sends data, and a server is the portion that receives.

Sending data through an IR connection uses the .NET Compact Framework class named IrDAClient defined in the System.Net.IrDA assembly, to which you have to add a reference in your project. For the sample that goes along with this and the next recipe, the form contains a large, multiline read-only TextBox control used as the chat transcript; a smaller, single-line TextBox , which is used to enter a message; and a corresponding Button to send the data. The send portion of the application resides within the Button 's Click event handler.

The first step in sending data is to create an IrDAClient . Pass an IrDAEndPoint object, a string denoting the service name , or an empty parameter list. The IrDAEndPoint contains a ServiceName property, which is the equivalent of sending in a single string parameter to the constructor. This ServiceName can be anything you want, but the receiving device must be listening for that service name for a connection to be made. This process is similar to that of ports used in sockets but uses a unique string value instead of an integer. If a ServiceName is not specified, which means you are creating an IrDAClient with an empty parameter list, you can create the IR connection by calling the Connect method and passing in the ServiceName there. Listing 26.4 is the initial portion of the Button event handler. If no connection is made within a specified time period, an exception is thrown. Therefore, you create a loop to allow a certain number of retries before giving up.

Listing 26.4 Using Infrared with Windows Forms
 using System; using System.Collections; using System.Windows.Forms; using System.Data; using System.Threading; using System.Net; using System.Net.Sockets; using System.IO; using System.Text; namespace _7_IRChatClient {     public class Form1 : System.Windows.Forms.Form     {         private System.Windows.Forms.TextBox tbTranscript;         private System.Windows.Forms.TextBox tbMessage;         private System.Windows.Forms.Button btnSend;         private System.Windows.Forms.MainMenu mainMenu1;         private System.Windows.Forms.MenuItem menuItem1;         private System.Windows.Forms.MenuItem mnuExit;         // the name used for this IR service         private string serviceType = "IRDA_CHAT";         public Form1()         {             InitializeComponent();         }         /* Windows Form Designer Generated Code */         private void AddMessage( string name, string message )         {             tbTranscript.Text += name + ": " + message + "\r\n";             tbTranscript.ScrollToCaret();         }         private void btnSend_Click(object sender, System.EventArgs e)         {             int numTries = 0;             const int numRetries = 5;             IrDAClient client = null;   // the client to send data to             // disable the send button and display the wait cursor             btnSend.Enabled = false;             Cursor.Current = Cursors.WaitCursor;             do             {                  try                  {                     // find a device to send data to                     client = new IrDAClient( serviceType );                 }                 catch( Exception ex )                 {                     if( numTries >= numRetries-1 )                     {                         // add a message to the transcript TextBox                         AddMessage("Error","cannot send message-"+ex.Message);                         // enable button, reset cursor, clear message TextBox                         btnSend.Enabled = true;                         tbMessage.Text = "";                         Cursor.Current = Cursors.Default;                         return;                      }                 }                 numTries++;             } while( (client == null) && (numTries < numRetries ));             // to be continued... 

At this point, if the code makes it past the do / while loop, a connection is made and data cannot be sent. The IR classes were designed similarly to the Socket classes, which means you utilize streams to send data to the other device. To get a Stream object, call the GetStream method defined in the IrDAClient class. Next, call the Write method from the Stream object passing a byte array, the offset to start at in the array, and the number of total bytes to send. For this example, the application sends the text contained in the message TextBox . To convert a string to a byte array, you use the GetBytes method defined in the Encoding.ASCII class. After the data is sent, the Stream and IrDAClient objects are closed and the application is reset and ready to send more data whenever the user clicks the send button, as shown in Listing 26.5.

Listing 26.5 Sending Data over Infrared
 Stream byteStream = null;     try     {         byteStream = client.GetStream();         byteStream.Write( Encoding.ASCII.GetBytes( tbMessage.Text ),             0, tbMessage.Text.Length );         AddMessage( "You", tbMessage.Text );     }     finally     {         if( byteStream != null )             byteStream.Close();         if( client != null )             client.Close();         btnSend.Enabled = true;         tbMessage.Text = "";         Cursor.Current = Cursors.Default;     } }  // end btnSend_Click 

Comments

Infrared communication between devices has been around for a number of years due to its immense popularity, especially for the transfer of contact information. Infrared on PDAs has given rise to a variety of different applications. For instance, some applications allow you to play multiplayer games by simply lining up the IR ports. Some applications even let you use your mobile device as a television remote control.

Chapter 15, "Sockets," described the notion of protocols. A protocol is simply a contract that is established between two systems for them to communicate effectively. The rules it enforces indicate what can and can't be sent between the two machines as well as the format of the data. This chapter developed an extremely simple protocol even though it didn't look like one. The protocol contained only two rules. The first rule was that a special service name must be used for IR chat application to communicate, and the name was arbitrarily chosen using a string value of IRDA_CHAT . The second rule concerned how data is transferred, which is by passing strings back and forth. Again, nothing major here and although everything is implied from the code, you should strive to establish a certain protocol when developing an application that utilizes IR communication. Additionally, if you are interested in communicating with another IR-capable device, you have to discover its service name and communicate using the protocol defined by that device.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net