using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Seyounth.Auto.Hs.Runtime.Scanner; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Text.Unicode; using System.Threading.Tasks; namespace Seyounth.Auto.Hs.Runtime.Printer { public class BoxPrinter : IPrinter { public int Id => 2; //扫到码后的业务逻辑 public event Action OnScanned; private DeviceConnectConfig DeviceConnectConfig; private TcpClient _tcp; private NetworkStream _stream; private readonly ILogger logger; private Queue _sendQueue = new Queue(); private CancellationTokenSource _cts = new CancellationTokenSource(); public BoxPrinter(IConfiguration configuration, ILogger logger) { /* * 从配置文件获取扫码枪IP/端口 */ var configs = configuration.GetSection("Printer").Get(); if (configs is not null && configs.Length > 0) { DeviceConnectConfig = configs.FirstOrDefault(e => e.Id == Id); } this.logger = logger; } /// /// 连接打印机 /// /// public async Task ConnectAsync() { while (true) { if (_tcp is not null) { try { _tcp.Dispose(); } catch (Exception ex) { /* * 忽略释放异常 */ } } _tcp = new TcpClient(); try { logger.LogInformation("打印机开始连接........"); await _tcp.ConnectAsync(new IPEndPoint(IPAddress.Parse(DeviceConnectConfig.IP), DeviceConnectConfig.Port)); if (_stream is not null) _stream.Dispose(); _stream = _tcp.GetStream(); if (_cts is not null && !_cts.IsCancellationRequested) _cts.Cancel(); logger.LogInformation("打印机连接成功"); _cts = new CancellationTokenSource(); SendAsync(_cts.Token); break; } catch (Exception ex) when (ex.GetBaseException() is OperationCanceledException oce || ex.GetBaseException() is SocketException socketException) { await Task.Delay(1000 * 5); logger.LogError(ex.GetBaseException(), "打印机连接失败,尝试重连中"); continue; } catch (Exception ex) { logger.LogError(ex, "打印机连接失败"); } } } /// /// 发送数据 /// /// private async Task SendAsync(CancellationToken token) { try { while (!token.IsCancellationRequested) { if (_sendQueue.Count > 0) { string content = _sendQueue.Peek(); var buffer = Encoding.UTF8.GetBytes(content); await _stream.WriteAsync(buffer, 0, buffer.Length); _ = _sendQueue.Dequeue(); } await Task.Delay(1000); } } catch (Exception ex) when (ex.GetBaseException() is OperationCanceledException oce || ex.GetBaseException() is SocketException socketException) { await ConnectAsync(); logger.LogError(ex.GetBaseException(), "打印失败"); } catch (Exception ex) { logger.LogError(ex, "打印失败"); } } /// /// 断开连接 /// /// /// public Task DisconnectAsync() { _cts.Cancel(); _tcp?.Dispose(); return Task.CompletedTask; } /// /// 打印数据 /// /// /// public async Task PrintAsync(string content) => _sendQueue.Enqueue(content); //{ // var buffer = Encoding.UTF8.GetBytes(content); // try // { // await _stream.WriteAsync(buffer,0, buffer.Length); // } // catch (Exception ex) // { // logger.LogError(ex,$"发送打印机数据失败,内容:{content}"); // } //} } }