pblbackend/DOAN.ServiceCore/DoanBackgroundService.cs

116 lines
3.8 KiB
C#
Raw Normal View History

2024-11-08 10:10:59 +08:00
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
{
2024-11-08 11:31:08 +08:00
public class DoanBackgroundService : IHostedService, IDisposable
2024-11-08 10:10:59 +08:00
{
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();
2024-11-08 11:31:08 +08:00
string[] address = storagelocation.PlcAddress2.Split(",");
for (int i = 0; i < address.Length; i++)
2024-11-08 10:10:59 +08:00
{
2024-11-08 11:31:08 +08:00
bool result = PLCTool.ReadBit(address[i]);
// 写补料日志
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;
inventorylog.CreatedBy = "PLC";
inventorylog.CreatedTime = DateTime.Now.ToLocalTime();
await DbScoped.SugarScope.CopyNew().Updateable(storagelocation).ExecuteCommandAsync();
2024-11-08 11:32:28 +08:00
await DbScoped.SugarScope.CopyNew().Insertable(inventorylog).ExecuteCommandAsync();
2024-11-08 11:31:08 +08:00
}
else
{
if (storagelocation.PackageNum <= 2)
{
//补料成功
storagelocation.PackageNum = 4;
inventorylog.Operation = 2;
inventorylog.PackageNum = 4;
inventorylog.CreatedBy = "PLC";
inventorylog.CreatedTime = DateTime.Now.ToLocalTime();
await DbScoped.SugarScope.CopyNew().Updateable(storagelocation).ExecuteCommandAsync();
2024-11-08 11:32:28 +08:00
await DbScoped.SugarScope.CopyNew().Insertable(inventorylog).ExecuteCommandAsync();
2024-11-08 11:31:08 +08:00
}
}
2024-11-08 10:10:59 +08:00
}
2024-11-08 11:31:08 +08:00
await Task.Delay(5000, stoppingToken);
Console.WriteLine("永驻线程正在读取plc值 " + result);
2024-11-08 10:10:59 +08:00
index++;
if (index > 16)
{
index = 1;
}
}
}
public void Dispose()
{
_cancellationTokenSource.Cancel();
_executingTask.Wait();
_cancellationTokenSource.Dispose();
}
}
}