Skip to content

Instantly share code, notes, and snippets.

@ciniml
Created January 26, 2020 06:42
Show Gist options
  • Save ciniml/92f04ff8d7530665bc8768f7e5f277ac to your computer and use it in GitHub Desktop.
Save ciniml/92f04ff8d7530665bc8768f7e5f277ac to your computer and use it in GitHub Desktop.
Serial port class for Unity on Linux
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
class SerialPort : IDisposable
{
[DllImport("libc.so.6", EntryPoint="open")]
private static extern int Open(string path, int mode);
[DllImport("libc.so.6", EntryPoint="close")]
private static extern int Close(int fd);
[DllImport("libc.so.6", EntryPoint="ioctl")]
private static extern int Ioctl(int fd, int request, int data);
[DllImport("libc.so.6", EntryPoint="read")]
private static extern int Read(int fd, byte[] data, int length);
[DllImport("libc.so.6", EntryPoint="write")]
private static extern int Write(int fd, byte[] data, int length);
private const int OPEN_READ_WRITE = 2;
public string Port {get; set;}
public int BaudRate {get; set;}
public bool IsOpen => this.fd != 0;
private int fd;
public SerialPort(string port, int baudRate)
{
this.Port = port;
this.BaudRate = baudRate;
}
public void Open()
{
this.fd = Open(this.Port, OPEN_READ_WRITE);
}
public void Close()
{
if( this.fd != 0 )
{
Close(this.fd);
}
}
public void Write(string message)
{
var decoded = System.Text.UTF8Encoding.UTF8.GetBytes(message);
Write(this.fd, decoded, decoded.Length);
}
public string ReadLine()
{
var buffer = new List<byte>();
var charBuffer = new byte[1];
for(;;)
{
if( Read(this.fd, charBuffer, 1) > 0 ) {
if( charBuffer[0] == 10 ) {
break;
}
else {
buffer.Add(charBuffer[0]);
}
}
}
return System.Text.UTF8Encoding.UTF8.GetString(buffer.ToArray());
}
public void Dispose()
{
this.Close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment