Showing posts with label BeginWrite. Show all posts
Showing posts with label BeginWrite. Show all posts

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;
        }