Files
sy_hx_pbl_backend/DOAN.ServiceCore/BackgroundService.cs
qianhao.xu b3dab7c8d6 ip 增加
2024-11-08 10:48:15 +08:00

111 lines
3.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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();
string[] address = storagelocation.PlcAddress2.Split(",");
for (int i = 0; i < address.Length; i++)
{
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();
}
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();
}
}
}
await Task.Delay(5000, stoppingToken);
Console.WriteLine("永驻线程正在读取plc值 " + result);
index++;
if (index > 16)
{
index = 1;
}
}
}
public void Dispose()
{
_cancellationTokenSource.Cancel();
_executingTask.Wait();
_cancellationTokenSource.Dispose();
}
}
}