I need to receive data from Serial Port A, convert and send it to Serial Port B. Now I am trying to use Raspberry And Raspberry OS to achieve this.
Here is my ConsoleApp coded by .net 5:
using System;
using System.IO.Ports;
using System.Linq;
using System.Threading.Tasks;
namespace ConsoleApp1
{
internal class Program
{
private static SerialPort SP1 = new SerialPort("/dev/ttyUSB0", 57600, Parity.None, 8, StopBits.One);
private static SerialPort SP2 = new SerialPort("/dev/ttyUSB1", 115200, Parity.None, 8, StopBits.One);
static void Main(string[] args)
{
SP1.DataReceived += SP_DataReceived;
try
{
SP1.Open();
SP2.Open();
}
catch(Exception ex){
Console.WriteLine(ex.Message);
}
Console.WriteLine("Started");
Console.ReadKey();
}
static List<byte> ByteList = new List<byte>();
private static void SP_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] buf = new byte[SP1.BytesToRead];
Console.WriteLine("DATA RECEIVED!");
SP1!.Read(buf, 0, buf.Length);
foreach (Byte b in buf)
{
ByteList.Add(b);
}
int StartIndex = -1;
int EndIndex = -1;
for (int i = 0; i < ByteList.Count; i++)
{
if (ByteList[i] == 2)
{
StartIndex = i;
}
else if (ByteList[i] == 13 && ByteList.Count-1 > i&&ByteList[i+1]==10)
{
EndIndex = i + 1;
break;
}
}
List<byte> NewByteList = new List<byte>();
if (StartIndex != -1 && EndIndex != -1)
{
for (int i = StartIndex+1; i <= EndIndex-2; i++)
{
NewByteList.Add(ByteList[i]);
}
}
ByteList.RemoveRange(StartIndex, EndIndex - StartIndex+1);
var Result = Encoding.UTF8.GetString(NewByteList.ToArray()).Split(" ").Last().Replace(Environment.NewLine, "");
if (!string.IsNullOrEmpty(Result))
{
Console.WriteLine(Result);
if (SP2.IsOpen)
{
SP2.Write(Result+Environment.NewLine);
}
else {
Console.WriteLine("SP2 is not opened");
}
}
}
}
}
The program runs well while input dotnet ConsoleApp1.dll
After I set it run at the device startup, I found raspberry os reports this by journalctl -f -u Console1App.service
:
Nov 08 07:22:42 raspberrypi dotnet-example[1412]: System.InvalidOperationException: Cannot read keys when either application does not have a console or when console input has been redirected. Try Console.Read.
Nov 08 07:22:42 raspberrypi dotnet-example[1412]: at System.ConsolePal.ReadKey(Boolean intercept)
Nov 08 07:22:42 raspberrypi dotnet-example[1412]: at System.Console.ReadKey()
Nov 08 07:22:42 raspberrypi dotnet-example[1412]: at ConsoleApp1.Program.Main(String[] args) in C:\Users\abc\Desktop\ConsoleApp1\ConsoleApp1\Program.cs:line 57
It seems because the startup of Linux has not any console. The console.read
of my program is just to block it exit automatically. How can I solve it?