syc_zhaoqianyan 66fc5b3b19 1.扫码枪实现
2.体重秤实现
3.打印机实现
2025-07-01 14:20:07 +08:00

155 lines
5.1 KiB
C#

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<string> OnScanned;
private DeviceConnectConfig DeviceConnectConfig;
private TcpClient _tcp;
private NetworkStream _stream;
private readonly ILogger<BoxPrinter> logger;
private Queue<string> _sendQueue = new Queue<string>();
private CancellationTokenSource _cts = new CancellationTokenSource();
public BoxPrinter(IConfiguration configuration, ILogger<BoxPrinter> logger)
{
/*
* 从配置文件获取扫码枪IP/端口
*/
var configs = configuration.GetSection("Printer").Get<DeviceConnectConfig[]>();
if (configs is not null && configs.Length > 0)
{
DeviceConnectConfig = configs.FirstOrDefault(e => e.Id == Id);
}
this.logger = logger;
}
/// <summary>
/// 连接打印机
/// </summary>
/// <returns></returns>
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, "打印机连接失败");
}
}
}
/// <summary>
/// 发送数据
/// </summary>
/// <returns></returns>
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, "打印失败");
}
}
/// <summary>
/// 断开连接
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public Task DisconnectAsync()
{
_cts.Cancel();
_tcp?.Dispose();
return Task.CompletedTask;
}
/// <summary>
/// 打印数据
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
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}");
// }
//}
}
}