-1

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?

Melon NG
  • 2,568
  • 6
  • 27
  • 52
  • 2
    The exception message says to try `Console.Read` did you try that instead of `Console.ReadKey` ? – Ramesh Nov 09 '21 at 01:41
  • @Ramesh I replaced Console.ReadKey with Console.Read. In spite it doesn't report any error now, in systemctl status ConsoleApp1.service it shows the program is exited. It seems Console.Read can not block the program from exiting. – Melon NG Nov 10 '21 at 02:18
  • @Ramesh Yes! That's what I need. – Melon NG Nov 16 '21 at 01:57

1 Answers1

0

You can use HostedService to keep your console application running all the time. The Microsoft doc explains how. Please read the documentation

I did this in a library I was developing for another job. You can look at readme as an example.

bugrakosen
  • 509
  • 3
  • 12
  • It seems won't work. It is used for Asp.net core while Asp.net core can't control hardware devices. – Melon NG Nov 10 '21 at 01:44
  • I think I misunderstood you. Is the problem keeping the application up and running or accessing the serial ports ? @Melon NG – bugrakosen Nov 10 '21 at 13:27
  • I code my program by .net core console App. I wanna keep the application up and running. HostedService is only available for asp.net core but not .net core console App. And also, as we know asp.net core can not access the serial port so I can't use the asp.net core. – Melon NG Nov 10 '21 at 13:34
  • Maybe you can try [this](https://stackoverflow.com/a/66519990/13092211) – bugrakosen Nov 11 '21 at 15:15
  • I tried @Ramesh 's way in here:https://stackoverflow.com/questions/2586612/how-to-keep-a-net-console-app-running. The accepted answer seems better. – Melon NG Nov 12 '21 at 00:43