Example #1
0
        /// <summary>
        /// Callback function for sender ready event
        /// </summary>
        /// <param name="ar"></param>
        private static void SendCallback(IAsyncResult ar)
        {
            // Retrieve the communication object from the state object.
            UARTCommunicator communicator = (UARTCommunicator)ar.AsyncState;

            try
            {
                // Retrieve serial port
                SerialPort serial_port = communicator.m_serial_port;

                // Complete sending the data to the remote device.
                serial_port.BaseStream.EndWrite(ar);

                Interlocked.Add(ref communicator.m_downstream_bytes, communicator.m_transmit_data_length);

                // Signal that all bytes have been sent.
                communicator.m_sender_lock.Release();

                // signal communication manager about the freed buffer
                communicator.m_communication_manager.GenerateEvent();
            }
            catch
            {
                // stop thread because of the unexpected error
                communicator.m_stop_requested = true;
                communicator.m_thread_event.Set();
            }
        }
Example #2
0
        /// <summary>
        /// Callback function for data received event
        /// </summary>
        /// <param name="ar"></param>
        private static void ReceiveCallback(IAsyncResult ar)
        {
            // Retrieve the communication object from the state object.
            UARTCommunicator communicator = (UARTCommunicator)ar.AsyncState;

            if (communicator == null)
            {
                return;
            }

            try
            {
                // Retrieve serial port
                SerialPort serial_port = communicator.m_serial_port;
                if (serial_port != null)
                {
                    // Read data from the remote device.
                    int bytes_read = serial_port.BaseStream.EndRead(ar);

                    if (bytes_read > 0)
                    {
                        communicator.m_received_data_length = bytes_read;
                        communicator.m_thread_event.Set();
                    }
                    else
                    {
                        communicator.m_read_pending = false;
                        communicator.m_thread_event.Set();
                    }
                }
            }
            catch
            {
                // stop thread because of the unexpected error
                communicator.m_stop_requested = true;
                communicator.m_thread_event.Set();
            }
        }