public Task Send(uint address, byte[] data) { Contract.Requires(data, "data") .NotToBeNull(); return(Task.Run(() => { uint transferredSize; var status = NativeMethods_I2C.I2C_DeviceWrite( this.ChannelHandle, address, (uint)data.Length, data, out transferredSize, WriteOptions | NativeMethods_I2C.TransferOptions.I2C_TRANSFER_OPTIONS_START_BIT | NativeMethods_I2C.TransferOptions.I2C_TRANSFER_OPTIONS_STOP_BIT); if (status != FTDI.FT_STATUS.FT_OK || transferredSize != data.Length) { throw new CommunicationException("Error while writing to the bus. (Status: " + status + ")"); } })); }
public Task <byte[]> Transceive(uint address, byte[] dataToSend, int receiveLength) { Contract.Requires(dataToSend, "dataToSend").NotToBeNull(); Contract.Requires(receiveLength, "receiveLength").ToBeInRange(x => x > 0); return(Task.Run(() => { uint transferredSize; // Send data var status = NativeMethods_I2C.I2C_DeviceWrite( this.ChannelHandle, address, (uint)dataToSend.Length, dataToSend, out transferredSize, WriteOptions | NativeMethods_I2C.TransferOptions.I2C_TRANSFER_OPTIONS_START_BIT); if (status != FTDI.FT_STATUS.FT_OK || transferredSize != dataToSend.Length) { throw new CommunicationException("Error while writing to the bus. (Status: " + status + ")"); } // Receive data var buffer = new byte[receiveLength]; status = NativeMethods_I2C.I2C_DeviceRead( this.ChannelHandle, address, (uint)receiveLength, buffer, out transferredSize, ReadOptions | NativeMethods_I2C.TransferOptions.I2C_TRANSFER_OPTIONS_START_BIT | NativeMethods_I2C.TransferOptions.I2C_TRANSFER_OPTIONS_STOP_BIT | NativeMethods_I2C.TransferOptions.I2C_TRANSFER_OPTIONS_NACK_LAST_BYTE); if (status != FTDI.FT_STATUS.FT_OK) { throw new CommunicationException("Error while reading from the bus. (Status: " + status + ")"); } if (transferredSize < receiveLength) { // If less bytes receive as expected => Copy to smaller array var tmpData = new byte[transferredSize]; Array.Copy(buffer, tmpData, transferredSize); buffer = tmpData; } return buffer; })); }