242 lines
9.6 KiB
C#
242 lines
9.6 KiB
C#
using Infrastructure.Attribute;
|
||
using Quartz;
|
||
using SqlSugar.IOC;
|
||
using System.Threading.Tasks;
|
||
using DOAN.Model.System;
|
||
using System.Net.Http;
|
||
using System;
|
||
using DOAN.Model.Bydlms.Dto;
|
||
using DOAN.Model.Bydlms;
|
||
using System.Collections.Generic;
|
||
using DOAN.Service.Bydlms.IBydlmsService;
|
||
using Infrastructure;
|
||
using Newtonsoft.Json;
|
||
using System.Text;
|
||
|
||
namespace DOAN.Tasks.TaskScheduler
|
||
{
|
||
/// <summary>
|
||
/// 定时任务
|
||
/// 使用如下注册后TaskExtensions里面不用再注册了
|
||
/// </summary>
|
||
[AppService(ServiceType = typeof(Job_SyncForward), ServiceLifetime = LifeTime.Scoped)]
|
||
public class Job_SyncForward : JobBase, IJob
|
||
{
|
||
//private readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||
private readonly string _BaseUrl = "http://10.17.2.198:3000/mock/24";
|
||
private readonly string _AlarmsUrl = "/api/product/Product_Information?System001_Warning";
|
||
private readonly string _StationPassesUrl = "/api/product/Product_Information?Product003_PassStation";
|
||
private readonly string _DeviceDataCollectionUrl = "/api/product/Product_Information?serviceId=Product005_EquipmentStatus";
|
||
private string _AttendanceRecordsUrl = "/api/product/Product_Information?System001_Warning";
|
||
|
||
public async Task Execute(IJobExecutionContext context)
|
||
{
|
||
await ExecuteJob(context, Run);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 任务使用中注意:所有方法都需要使用异步,并且不能少了await
|
||
/// </summary>
|
||
/// <returns></returns>
|
||
public async Task Run()
|
||
{
|
||
await Task.Delay(1000 * 10);
|
||
//TODO 业务逻辑
|
||
//var db = DbScoped.SugarScope;
|
||
|
||
//var info = await db.Queryable<SysDept>().FirstAsync();
|
||
//System.Console.WriteLine("job test");
|
||
|
||
try
|
||
{
|
||
Console.WriteLine("后台任务执行!");
|
||
// 报警信息转发
|
||
await ProcessAlarms(_BaseUrl + _AlarmsUrl);
|
||
|
||
// TODO 过站信息转发
|
||
await ProcessStationPasses(_BaseUrl + _StationPassesUrl);
|
||
|
||
// TODO 设备数采信息转发
|
||
// await ProcessDeviceDataCollection(BaseUrl + DeviceDataCollectionUrl);
|
||
|
||
// TODO 考勤打卡信息转发
|
||
// await ProcessAttendanceRecords(AttendanceRecordsUrl);
|
||
}
|
||
catch (HttpRequestException e)
|
||
{
|
||
// 捕获并处理HTTP请求异常
|
||
HandleHttpRequestException(e);
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
// 捕获并处理其他异常
|
||
HandleGeneralException(e);
|
||
}
|
||
|
||
|
||
}
|
||
/// <summary>
|
||
/// 处理报警信息转发。
|
||
/// </summary>
|
||
/// <param name="url">API URL。</param>
|
||
/// <returns>表示异步操作的任务。</returns>
|
||
private async Task ProcessAlarms(string url)
|
||
{
|
||
try
|
||
{
|
||
var db = DbScoped.SugarScope;
|
||
using (var tran = db.Ado.UseTran())
|
||
{
|
||
// 获取报警未上传信息
|
||
var list = db.Queryable<BydAlarmMsg>().Where(it => it.IsUpload == 0).OrderBy(it => it.Id).ToList();
|
||
if (list.Count > 0)
|
||
{
|
||
// 发送HTTP请求并获取响应内容
|
||
AlarmUploadData uploadData =
|
||
new()
|
||
{
|
||
serviceId = list[0].ServiceId,
|
||
factoryCode = list[0].FactoryCode,
|
||
data = list
|
||
};
|
||
string responseBody = await SendRequestAsync(url, uploadData);
|
||
|
||
// 标记报警信息已上传
|
||
var updateRes = db.Updateable(list)
|
||
.SetColumns(it => it.IsUpload == 1)
|
||
// .UpdateColumns(it => new { it.IsUpload })
|
||
.ExecuteCommand();
|
||
if (updateRes == 0)
|
||
{
|
||
Console.WriteLine("报警信息上传失败!======== " + responseBody);
|
||
throw new Exception("Failed to mark alarms as uploaded.");
|
||
}
|
||
else
|
||
{
|
||
Console.WriteLine("报警信息上传成功!======== " + responseBody);
|
||
}
|
||
}
|
||
|
||
// 提交事务
|
||
tran.CommitTran();
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
throw;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 处理过站信息转发。
|
||
/// </summary>
|
||
/// <returns>表示异步操作的任务。</returns>
|
||
private async Task ProcessStationPasses(string url)
|
||
{
|
||
|
||
try
|
||
{
|
||
var db = DbScoped.SugarScope;
|
||
using (var tran = db.Ado.UseTran())
|
||
{
|
||
// 获取过站未上传信息
|
||
var list = db.Queryable<BydProductionStation>().Where(it => it.IsUpload == 0).OrderBy(it => it.Id).ToList();
|
||
if (list.Count > 0)
|
||
{
|
||
// 发送HTTP请求并获取响应内容
|
||
ProductionStationUploadData uploadData =
|
||
new()
|
||
{
|
||
AutoBindBatchMaterial = true,
|
||
serviceId = "Product003_PassStation",
|
||
factoryCode = "ZZG4",
|
||
requestTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
|
||
MesUrl = "http://zz-mes-fddl01.byd.com/",
|
||
MesVersion = "3",
|
||
Remote = "10.79.80.56",
|
||
Timer = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
|
||
Uuid = Guid.NewGuid().ToString(),
|
||
RePushSend = 0,
|
||
data = list
|
||
};
|
||
string responseBody = await SendRequestAsync(url, uploadData);
|
||
|
||
// 标记信息已上传
|
||
var updateRes = db.Updateable(list).SetColumns(it => it.IsUpload == 1)
|
||
// .UpdateColumns(it => new { it.IsUpload })
|
||
.ExecuteCommand();
|
||
if (updateRes == 0)
|
||
{
|
||
Console.WriteLine("过站信息上传失败!======== " + responseBody);
|
||
throw new Exception("Failed to mark alarms as uploaded.");
|
||
}
|
||
else
|
||
{
|
||
Console.WriteLine("过站信息上传成功!======== " + responseBody);
|
||
}
|
||
}
|
||
|
||
// 提交事务
|
||
tran.CommitTran();
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
throw;
|
||
}
|
||
}
|
||
/// <summary>
|
||
/// 发送HTTP POST请求并返回响应内容。
|
||
/// </summary>
|
||
/// <param name="url">API URL。</param>
|
||
/// <param name="data">要发送的数据对象。</param>
|
||
/// <returns>API响应的内容字符串。</returns>
|
||
private async Task<string> SendRequestAsync(string url, object data)
|
||
{
|
||
// 将数据对象序列化为JSON字符串
|
||
var jsonData = JsonConvert.SerializeObject(data);
|
||
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
|
||
|
||
// 创建HTTP请求消息
|
||
using (var request = new HttpRequestMessage(HttpMethod.Post, url))
|
||
{
|
||
request.Content = content; // 设置请求体内容
|
||
request.Headers.Add("appId", "61320D6EEF5A48B7C32149DF991BED41"); // 添加请求头
|
||
request.Headers.Add("appKey", "85725BB0BCCEE8DB1AE2D5A48D393ABE"); // 添加请求头
|
||
using HttpClient client = new HttpClient();
|
||
// 发送HTTP请求并获取响应
|
||
HttpResponseMessage response = await client.SendAsync(request);
|
||
|
||
// 确保响应状态码成功
|
||
if (!response.IsSuccessStatusCode)
|
||
{
|
||
throw new HttpRequestException($"请求发送失败: {response.StatusCode}");
|
||
}
|
||
|
||
// 读取并返回响应内容
|
||
return await response.Content.ReadAsStringAsync();
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 处理HTTP请求异常。
|
||
/// </summary>
|
||
/// <param name="exception">捕获的HttpRequestException异常。</param>
|
||
private void HandleHttpRequestException(HttpRequestException exception)
|
||
{
|
||
Console.WriteLine($"HTTP Request Error: {exception.Message}");
|
||
// 可以在这里添加日志记录或其他处理逻辑
|
||
}
|
||
|
||
/// <summary>
|
||
/// 处理一般异常。
|
||
/// </summary>
|
||
/// <param name="exception">捕获的一般异常。</param>
|
||
private void HandleGeneralException(Exception exception)
|
||
{
|
||
Console.WriteLine($"General Error: {exception.Message}");
|
||
// 可以在这里添加日志记录或其他处理逻辑
|
||
}
|
||
}
|
||
}
|