Xamarin Android Serial Port

Permalink

How to write to serial port? June 2016 in Xamarin.Android. I have a project where I am trying to convert a Windows based app that sends data over USB/serial to. XamarinUsbSerial was a C# wrapper for the Java usb-serial-for-android. It used an older version of the usb-serial-for-android.jar file. UsbSerialForAndroid is a 100% C# port of the original java code. I'm using a bluetooth to serial device. The bluetooth to serial device is a bolutek BK-MD-BC04-BDEMO. It's basically a bluetooth device with a serial port on it. I am able to connect to the device using my Android phone, and I can send data to it. With my computer connected to the serial port on the bluetooth device using PuTTY on COM5 with. Serial Port wrapper for Xamarin.Android. Contribute to officialdoniald/Xamarin.Android.SerialPort development by creating an account on GitHub. A Xamarin port of the usb-serial-for-android library Back in January, I ported the excellent usb-serial-for-android library from the Java source code to Xamarin C#. We have an Android application that needs to use an external RFID reader. The reader is an Elatec TWN4 RFID reader and it can work as virtual comm port over USB.

Join GitHub today

GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.

Sign up
Find file Copy path
Cannot retrieve contributors at this time

Xamarin Android Bluetooth Serial Port

Xamarin vs android studio
usingJava.Lang;
usingJava.Nio;
usingJava.Nio.Charset;
usingSerial;
usingSystem;
usingNativeSerialPort=Serial.Serial;
usingSerialPortBuilder=Serial.Serial.Builder;
namespaceSerialPort.SerialPortWrapper
{
/// <summary>
/// Native Serial Port wrapper. More information: https://github.com/chzhong/serial-android.
/// </summary>
publicclassSerialPort
{
/// <summary>
/// This is the native SerialPort. We can use this as a SerialPort.
/// </summary>
privateNativeSerialPort_serialPort;
/// <summary>
/// Stop the reading from the Serial Port.
/// </summary>
privatebool_stopOnReceive=true;
/// <summary>
/// Read from the Serial Port and send the readed datas to the subscribers.
/// </summary>
publiceventEventHandler<SerialPortEventArgs> OnReceived;
protectedvirtualvoidOnReceived_Event(SerialPortEventArgse)
{
OnReceived?.Invoke(this, e);
}
/// <summary>
/// Read from the Serial Port.
/// </summary>
private System.Threading.ThreadOnReceiveThread;
/// <summary>
/// Create new SerialPort from the native library: libserial-release.aar.
/// Creates a Serial object and opens the port if a port is specified, otherwise it remains closed until serial::Serial::open is called.
/// @throws SerialException Generic serial error.
/// @throws SerialIOException I/O error.
/// @throws IllegalArgumentException Invalid arguments are given.
/// </summary>
/// <paramname='device'>A string containing the address of the serial port, which would be something like 'COM1' on Windows and '/dev/ttyS0' on Linux.</param>
/// <paramname='baudrate'>An unsigned 32-bit integer that represents the baudrate.</param>
/// <paramname='stopbits'>Number of stop bits used, default is stopbits_one, possible values are: stopbits_one, stopbits_one_point_five, stopbits_two.</param>
/// <paramname='parity'>Method of parity, default is parity_none, possible values are: parity_none, parity_odd, parity_even.</param>
/// <paramname='byteSize'>Size of each byte in the serial transmission of data, default is eightbits, possible values are: fivebits, sixbits, sevenbits, eightbits.</param>
/// <paramname='flowControl'>Flowcontrol Type of flowcontrol used, default is flowcontrol_none, possible values are: flowcontrol_none, flowcontrol_software, flowcontrol_hardware.</param>
/// <paramname='timeout'>A serial::Timeout struct that defines the timeout conditions for the serial port. inter_byte_timeout,read_timeout_constant,read_timeout_multiplier,write_timeout_constant,write_timeout_multiplier</param>
publicSerialPort(
stringdevice,
intbaudrate,
Stopbitsstopbits,
Parityparity,
ByteSizebyteSize,
FlowControlflowControl,
Timeouttimeout)
{
SerialPortBuilderSerial=newSerialPortBuilder(
device,
baudrate,
stopbits,
parity,
byteSize,
timeout,
flowControl);
OnReceiveThread=newSystem.Threading.Thread(()=>
{
while (!_stopOnReceive)
{
varbuffer=Read();
if (buffer!=null&&buffer.Length>0)
{
OnReceived(this, newSerialPortEventArgs() { Data=buffer });
}
}
});
OnReceiveThread.IsBackground=true;
OnReceiveThread.Start();
_serialPort=Serial.NativeSerialPort;
}
/// <summary>
/// Read a given amount of bytes from the serial port into a given buffer. The read function will return in one of three cases: The number of requested bytes was read. In this case the number of bytes requested will match the size_t returned by read. A timeout occurred, in this case the number of bytes read will not match the amount requested, but no exception will be thrown. One of two possible timeouts occurred: The inter byte timeout expired, this means that number of milliseconds elapsed between receiving bytes from the serial port exceeded the inter byte timeout. The total timeout expired, which is calculated by multiplying the read timeout multiplier by the number of requested bytes and then added to the read timeout constant. If that total number of milliseconds elapses after the initial call to read a timeout will occur. An exception occurred, in this case an actual exception will be thrown.
/// @throws SerialIOException I/O Error.
/// </summary>
/// <paramname='buffer'>An array of at least the requested size.</param>
/// <paramname='offset'>the offset of the buffer to receive data.</param>
/// <paramname='size'>How many bytes to be read.</param>
/// <returns>A size_t representing the number of bytes read as a result of the call to read.</returns>
publicintRead(byte[] buffer, intoffset, intsize)
{
return_serialPort.Read(buffer, offset, size);
}
/// <summary>
/// Read all data available from the serial port.
/// @throws SerialIOException I/O Error.
/// </summary>
/// <returns>A buffer that contains all available data.</returns>
publicbyte[] Read()
{
return_serialPort.Read();
}
/// <summary>
/// Read a given amount of bytes from the serial port into a give buffer.
/// @throws SerialIOException I/O Error.
/// </summary>
/// <paramname='buffer'>A reference to a std::vector of uint8_t.</param>
/// <paramname='size'>A size_t defining how many bytes to be read.</param>
/// <returns>A size_t representing the number of bytes read as a result of the call to read.</returns>
publicintRead(ByteBufferbuffer, intsize)
{
return_serialPort.Read(buffer, size);
}
/// <summary>
/// Read a given amount of bytes from the serial port into a give buffer.
/// @throws SerialIOException I/O Error.
/// </summary>
/// <paramname='buffer'>A reference to a std::string.</param>
/// <paramname='size'>A size_t defining how many bytes to be read.</param>
/// <paramname='charset'>The charset of the data.</param>
/// <returns>A size_t representing the number of bytes read as a result of the call to read.</returns>
publicintRead(StringBuilderbuffer, intsize/*= 1*/, Charsetcharset)
{
return_serialPort.Read(buffer, size, charset);
}
/// <summary>
/// Read a given amount of bytes from the serial port and return a string containing the data.
/// @throws SerialIOException I/O Error.
/// </summary>
/// <paramname='size'>A size_t defining how many bytes to be read.</param>
/// <paramname='charset'>A std::string containing the data read from the port.</param>
/// <returns></returns>
publicstringRead(intsize, Charsetcharset)
{
return_serialPort.Read(size, charset);
}
/// <summary>
/// Reads in a line or until a given delimiter has been processed. Reads from the serial port until a single line has been read.
/// @throws SerialIOException I/O Error.
/// </summary>
/// <paramname='buffer'>A std::string reference used to store the data.</param>
/// <paramname='size'>A maximum length of a line, defaults to 65536 (2^16).</param>
/// <paramname='eol'>A string to match against for the EOL.</param>
/// <returns>A size_t representing the number of bytes read.</returns>
publicintReadLine(StringBuilderbuffer, intsize/*= 65536*/, stringeol/*= 'n'*/)
{
return_serialPort.Readline(buffer, size, eol);
}
/// <summary>
/// Reads in a line or until a given delimiter has been processed. Reads from the serial port until a single line has been read.
/// @throws SerialIOException I/O Error.
/// </summary>
/// <paramname='size'>A maximum length of a line, defaults to 65536 (2^16).</param>
/// <paramname='eol'>A string to match against for the EOL.</param>
/// <returns>A std::string containing the line.</returns>
publicstringReadLine(intsize/*= 65536*/, stringeol/*= 'n'*/)
{
return_serialPort.Readline(size, eol);
}
/// <summary>
/// Reads in multiple lines until the serial port times out. This requires a timeout > 0 before it can be run.It will read until a Timeout occurs and return a list of strings.
/// @throws SerialIOException I/O Error.
/// </summary>
/// <paramname='size'>A maximum length of combined lines, defaults to 65536 (2^16)</param>
/// <paramname='eol'>A string to match against for the EOL.</param>
/// <returns>A array containing the lines.</returns>
publicstring[] ReadLines(intsize/*= 65536*/, stringeol/*= 'n'*/)
{
return_serialPort.Readlines(size, eol);
}
/// <summary>
/// Write a byte[] to the serial port.
/// @throws SerialIOException I/O Error.
/// </summary>
/// <paramname='data'>A const reference containing the data to be written to the serial port.</param>
/// <paramname='size'>A size_t that indicates how many bytes should be written from the given data buffer.</param>
/// <returns>A size_t representing the number of bytes actually written to.</returns>
publicintWrite(byte[] data, intsize)
{
return_serialPort.Write(data, size);
}
/// <summary>
/// Write the string on the SerialPort.
/// </summary>
/// <paramname='text'></param>
publicvoidWrite(stringtext)
{
_serialPort.Write(text);
}
/// <summary>
/// Write the string and a new line on the SerialPort.
/// </summary>
/// <paramname='text'></param>
publicvoidWriteLine(stringtext)
{
_serialPort.Write(text+'n');
}
/// <summary>
/// Flush the input and output buffers.
/// </summary>
publicvoidFlush()
{
_serialPort.Flush();
}
/// <summary>
/// Flush only the input buffer.
/// </summary>
publicvoidFlushInput()
{
_serialPort.FlushInput();
}
/// <summary>
/// Flush only the output buffer.
/// </summary>
publicvoidFlushOutput()
{
_serialPort.FlushOutput();
}
/// <summary>
/// Set the RTS handshaking line to the true level.
/// </summary>
publicvoidSetRTS()
{
_serialPort.SetRTS();
}
/// <summary>
/// Set the RTS handshaking line to the given level.
/// </summary>
/// <paramname='level'></param>
publicvoidSetRTS(boollevel)
{
_serialPort.SetRTS(level);
}
/// <summary>
/// Set the DTR handshaking line to the given level.
/// </summary>
publicvoidSetDTR()
{
_serialPort.SetDTR();
}
/// <summary>
/// Set the DTR handshaking line to the given level.
/// </summary>
/// <paramname='level'></param>
publicvoidSetDTR(boollevel)
{
_serialPort.SetDTR(level);
}
/// <summary>
/// Sends the RS-232 break signal.
/// </summary>
/// <paramname='duration'></param>
publicvoidSendBreak(intduration)
{
_serialPort.SendBreak(duration);
}
/// <summary>
/// Set the break condition to true level.
/// </summary>
publicvoidSetBreak()
{
_serialPort.SetBreak();
}
/// <summary>
/// Set the break condition to a given level.
/// </summary>
/// <paramname='level'></param>
publicvoidSetBreak(boollevel)
{
_serialPort.SetBreak(level);
}
/// <summary>
/// Close the Serial Port.
/// </summary>
publicvoidClose()
{
_serialPort.Close();
}
/// <summary>
/// Stop the Receiving Thread.
/// </summary>
publicvoidStopReceive()
{
_stopOnReceive=true;
}
/// <summary>
/// Start the Receiving Thread.
/// </summary>
publicvoidStartReceive()
{
_stopOnReceive=false;
}
/// <summary>
/// Blocks until CTS, DSR, RI, CD changes or something interrupts it.
/// Can throw an exception if an error occurs while waiting.
/// You can check the status of CTS, DSR, RI, and CD once this returns.
/// Uses TIOCMIWAIT via ioctl if available (mostly only on Linux) with a
/// resolution of less than +-1ms and as good as +-0.2ms. Otherwise a
/// polling method is used which can give +-2ms.
/// @throws SerialException
/// </summary>
/// <returns>Returns true if one of the lines changed, false if something else occurred.</returns>
publicboolWaitForChange()
{
return_serialPort.WaitForChange();
}
}
}

Xamarin Android Usb Example

  • Copy lines
  • Copy permalink