pblbackend/DOAN.ServiceCore/BackgroundService.cs
2024-11-08 10:10:59 +08:00

97 lines
2.9 KiB
C#

using System;
using System.Threading;
using System.Threading.Tasks;
using DOAN.Infrastructure.PLC;
using DOAN.Model.PBL;
using DOAN.Model.System;
using Microsoft.Extensions.Hosting;
using SqlSugar;
using SqlSugar.IOC;
namespace DOAN.ServiceCore
{
public class DoanBackgroundService : IHostedService, IDisposable
{
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private Task _executingTask;
public Task StartAsync(CancellationToken cancellationToken)
{
PLCTool.ConnectPLC();
// 当服务开始时,启动后台任务
_executingTask = ExecuteAsync(_cancellationTokenSource.Token);
return _executingTask.IsCompleted ? _executingTask : Task.CompletedTask;
}
public async Task StopAsync(CancellationToken cancellationToken)
{
// 请求取消后台任务
_cancellationTokenSource.Cancel();
// 等待后台任务完成
await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken));
}
private async Task ExecuteAsync(CancellationToken stoppingToken)
{
// 获取所有传感器 地址
int index = 1;
while (!stoppingToken.IsCancellationRequested)
{
Storagelocation storagelocation = await DbScoped.SugarScope.CopyNew()
.Queryable<Storagelocation>().Where(it => it.Id == index).FirstAsync();
bool result = PLCTool.ReadBit(storagelocation.PlcAddress2);
// 写补料日志
Inventorylog inventorylog = new Inventorylog();
inventorylog.Id = SnowFlakeSingle.Instance.NextId().ToString();
inventorylog.RackCode = storagelocation.RackCode;
if (result)
{
//缺料
storagelocation.PackageNum = 2;
inventorylog.Operation = 1;
inventorylog.PackageNum = 2;
}
else
{
//补料
storagelocation.PackageNum = 4;
inventorylog.Operation = 2;
inventorylog.PackageNum = 4;
}
inventorylog.CreatedBy = "PLC";
inventorylog.CreatedTime = DateTime.Now.ToLocalTime();
await DbScoped.SugarScope.CopyNew().Insertable(storagelocation).ExecuteCommandAsync();
await Task.Delay(3000, stoppingToken);
index++;
if (index > 16)
{
index = 1;
}
}
}
public void Dispose()
{
_cancellationTokenSource.Cancel();
_executingTask.Wait();
_cancellationTokenSource.Dispose();
}
}
}