I am trying to developing a program with asp.net mvc 5 that sends and receives commands from the serial port on the server side. Actually, I have a piece of hardware that is connected to the server and I want to send command to this hardware and get a Response from that.
This is the method I use to send the data :
public static void SendData(string data )
{
SerialPort port = new SerialPort(
"COM5", 9600, Parity.None, 8, StopBits.One);
port.Open();
port.Write(data);
port.Close();
}
and this is my receive method:
public static void ReceiveData()
{
if (port != null && port.IsOpen)
port.Close();
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
port.Open();
}
public static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int dataLength = port.BytesToRead;
byte[] data = new byte[dataLength];
int nbrDataRead = port.Read(data, 0, dataLength);
if (nbrDataRead == 0)
return;
Taxi.Controllers.ReceiveController.Decision(System.Text.Encoding.UTF8.GetString(data));
}
I have a problem with my receive method. Every time my hardware sends string, I can just see last character of them in my Index view. I am wondering how I could create a receive method that receives all characters of posted string.
i found my answer finally. this is about Interference on send speed in serial port and receive(calculate) speed in server ! you should set sleep time in first line of "port_DataReceived" method, as you see:
public static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(TimeSpan.FromMilliseconds(100));
int dataLength = port.BytesToRead;
char[] result = new char[dataLength];
for (int len = 0; len < result.Length;)
{
len += port.Read(result, len, result.Length - len);
}
string send = "";
for (int i = 0; i < result.Length; i++)
{
send += result[i];
}
Taxi.Controllers.ReceiveController.Decision(send);
}