using Barcode.Host.Server.Models; using Barcode.Host.Shared.Models.Stateless; using System.Text; namespace Barcode.Host.Server.Services; public class SerialService : ISerialService { private string _LastRaw; private readonly AppSettings _AppSettings; private readonly System.IO.Ports.SerialPort? _SerialPort; public SerialService(AppSettings appSettings) { _LastRaw = string.Empty; _AppSettings = appSettings; if (string.IsNullOrEmpty(appSettings.SerialPortName)) _SerialPort = null; else _SerialPort = new(appSettings.SerialPortName, 9600) { ReadTimeout = 2 }; } void ISerialService.Open() => _SerialPort?.Open(); void ISerialService.Close() => _SerialPort?.Close(); void ISerialService.SerialPortWrite(int count, string raw) { if (raw != _LastRaw) { string message; if (count == _AppSettings.ExpectedScanLengthA) message = $" {raw[2..]} {DateTime.Now:h:m tt}"; else if (count == _AppSettings.ExpectedScanLengthB) message = $" {raw[2..]}"; else message = $" {raw}"; byte[] bytes = Encoding.ASCII.GetBytes(message); _SerialPort?.Write(bytes, 0, bytes.Length); _LastRaw = raw; } } }