Friday, May 31, 2013

Bluetooth Chat Screens

For learning I put together a Bluetooth chat client.  I used sample code from the InTheHand examples to get this to work.  

I decided to store devices in a config file instead of trying to discover clients.  The discovery takes too much time on these devices.  Another advantage of storing Bluetooth addresses in a config file is these devices can remain in non discovery mode. 

I can send the source code to anyone interested.  

thanks.





Friday, May 17, 2013

Asynchronous write and read using InTheHand 32Feet Bluetooth serial communications

With the connection all ready opened:


public class MyAsyncInfo
        {
            public Byte[] ByteArray { get; set; }
            public Stream MyStream { get; set; }

            public MyAsyncInfo(Byte[] array, Stream stream)
            {
                ByteArray = array;
                MyStream = stream;
            }
        }

        private void CASMonitor_SendData()
        {
            byte[] data = new byte[4];
            data[0] = 0x58;
            data[1] = 0x30;
            data[2] = 0x39;
            data[3] = 0x0D;


            try
            {
                stream.BeginWrite(data, 0, data.Length, WriteComplete, null);
            }
            catch (Exception ee)
            {
                MessageBox.Show("Error: Sending, Verify Bluetooth Connection");
            }
        }

        private void WriteComplete(IAsyncResult ar)
        {
            try
            {
                stream.EndWrite(ar);

                byte[] DeviceBuffer = new byte[100];
                DeviceBuffer.Initialize();

                Stream DeviceStream = null;
                DeviceStream = btClient.GetStream();
                DeviceStream.Flush();

                DeviceStream.BeginRead(DeviceBuffer, 0, DeviceBuffer.Length, DeviceReadComplete, new MyAsyncInfo(DeviceBuffer, DeviceStream));

            }
            catch (Exception ex)
            {
                MessageBox.Show("write error");
            }
        }

        private void DeviceReadComplete(IAsyncResult r)
        {
            int numbytes = 0;
            MyAsyncInfo info = r.AsyncState as MyAsyncInfo;

            try
            {
                numbytes = info.MyStream.EndRead(r);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Readcomplete ex " + ex.Message);

                return;
            }

            string msg = System.Text.Encoding.Default.GetString(info.ByteArray, 0, numbytes);

            if ((info.ByteArray[0] == 'X') && (info.ByteArray[1] == '0') && (info.ByteArray[2] == '9') && (numbytes == 24))
            {
                ProcessDataProc(msg, numbytes);
            }
            else
            {
                if (_retryCnt < 3)
                {
                    CASMonitor_SendData();
                    return;
                }
            }

            return;
        }