using System; using System.IO.Ports; using Microsoft.VisualStudio.TestTools.UnitTesting; using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.hexLogger; using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.protocolCommons; using TBF.Rig.TestMethods.iPerlCommunication.communication.C4.wiredProtocol; namespace TBFTests.Rig.RegisterReaders.iPerlASICReader.communication.C4.wiredProtocol { [TestClass] public class TouchReadBaudRateDetectionTests { private const string ComPort = "COM3"; // COM PORT OF THE ASIC private const int ReadTimeoutMs = 1500; private static readonly int[] StandardBaudRates = { 115200, 9600//, 10400, 15625, 18432, 19200, 31250, 36864, //38400, 50000, 57600, 62500, 76800, //1200, 2400, 4800, 7812 }; [TestMethod] [TestCategory("Hardware")] [TestCategory("Serial")] public void Detect_BaudRate_By_ViewFactoryId() { byte[] request = new TouchReadFrameBuilder() .RequestResponse(true) .AddCommand(ProtocolCommand.Simple) .BuildBytes(); var parser = new TouchReadFrameParser(); foreach (int baud in StandardBaudRates) { Console.WriteLine($"--- Testing baud rate: {baud} ---"); try { using (var port = new SerialPort(ComPort, baud, Parity.None, 8, StopBits.One)) { port.ReadTimeout = ReadTimeoutMs; port.WriteTimeout = 500; port.Open(); port.DiscardInBuffer(); port.DiscardOutBuffer(); Console.WriteLine("TX → " + HexFormatter.ToSerialHex(request)); port.Write(request, 0, request.Length); byte[] response = ReadFullFrame(port); Console.WriteLine("RX ← " + HexFormatter.ToSerialHex(response)); TouchReadResponse decoded = parser.Parse(response); if (decoded.IsOk) { string factoryId = decoded.GetAsciiPayload(); Console.WriteLine(); Console.WriteLine("VALID RESPONSE"); Console.WriteLine("Baud rate : " + baud); Console.WriteLine("Factory ID : " + factoryId); Console.WriteLine(); Assert.IsFalse(string.IsNullOrEmpty(factoryId), "Factory ID is empty"); return; // SUCCESS → stop scanning } } } catch (TimeoutException) { Console.WriteLine("Timeout"); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } } Assert.Fail("No valid baud rate detected."); } private static byte[] ReadFullFrame(SerialPort port) { byte start = (byte)port.ReadByte(); if (start != 0x0D) throw new InvalidOperationException("Invalid START byte"); byte length = (byte)port.ReadByte(); int remaining = length; byte[] buffer = new byte[2 + remaining]; buffer[0] = start; buffer[1] = length; int offset = 2; while (remaining > 0) { int read = port.Read(buffer, offset, remaining); offset += read; remaining -= read; } return buffer; } [TestMethod] public void ConvertTest() { byte[] input = { 0x53, 0x57, 0x05, 0x01, 0x0D }; Console.WriteLine(HexFormatter.ToSerialHex(input)); Console.WriteLine(HexFormatter.ToHex(input)); } } }