262 lines
11 KiB
C#
262 lines
11 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;
|
||
using Azure;
|
||
|
||
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 _BaseUrl = "http://10.79.7.45:8088/mesOpenServer";
|
||
private readonly string _AlarmsUrl = "/api/product/Product_Information?System001_Warning";
|
||
//private readonly string _StationPassesUrl = "/api/product/Product_Information?Product003_PassStation";
|
||
private readonly string _StationPassesUrl = "/api/product/Product_Information";
|
||
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 * 1);
|
||
//TODO 业务逻辑
|
||
//var db = DbScoped.SugarScope;
|
||
|
||
//var info = await db.Queryable<SysDept>().FirstAsync();
|
||
//System.Console.WriteLine("job test");
|
||
|
||
try
|
||
{
|
||
// TODO 过站信息转发
|
||
await ProcessStationPasses(_BaseUrl + _StationPassesUrl);
|
||
// 报警信息转发
|
||
await ProcessAlarms(_BaseUrl + _AlarmsUrl);
|
||
|
||
// 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();
|
||
Console.WriteLine($"本次报警未上传信息,数据大小为{list.Count}");
|
||
if (list.Count > 0)
|
||
{
|
||
// 发送HTTP请求并获取响应内容
|
||
AlarmUploadData uploadData =
|
||
new()
|
||
{
|
||
serviceId = "System001_Warning",
|
||
factoryCode = list[0].FactoryCode,
|
||
data = list
|
||
};
|
||
string responseBody = await SendRequestAsync(url, uploadData);
|
||
|
||
// 标记报警信息已上传
|
||
foreach (var item in list)
|
||
{
|
||
item.IsUpload = 1;
|
||
}
|
||
var updateRes = db.Updateable(list)
|
||
.UpdateColumns(it => new { it.IsUpload })
|
||
// .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)
|
||
{
|
||
Console.WriteLine($"执行过站信息上传!================================");
|
||
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();
|
||
Console.WriteLine($"本次过站未上传信息,数据大小为{list.Count}");
|
||
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);
|
||
// 标记信息已上传
|
||
foreach (var item in list)
|
||
{
|
||
item.IsUpload = 1;
|
||
}
|
||
var updateRes = db.Updateable(list)
|
||
.UpdateColumns(it => new { it.IsUpload })
|
||
// .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)
|
||
{
|
||
Console.WriteLine("过站信息上传出现异常!======== " + ex.Message);
|
||
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)
|
||
{
|
||
if (data == null) {
|
||
throw new HttpRequestException($"请求发送失败: 请求体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", "7A5D0E17337C574DA1B6BAE22AC8B635");
|
||
request.Headers.Add("appKey", "501546E35229E5725B9765568B461BB2");
|
||
using HttpClient client = new HttpClient();
|
||
// 发送HTTP请求并获取响应
|
||
HttpResponseMessage response = await client.SendAsync(request);
|
||
string responseBody = await response.Content.ReadAsStringAsync();
|
||
// 确保响应状态码成功
|
||
if (!response.IsSuccessStatusCode || response == null)
|
||
{
|
||
// Console.WriteLine($"==1===请求响应失败,状态码: {response.StatusCode}");
|
||
// Console.WriteLine($"==2===请求响应失败,发送url: {url}");
|
||
// Console.WriteLine($"==3===请求响应失败,发送body内容: {jsonData}");
|
||
// Console.WriteLine($"==4===请求响应失败,请求内容: {response.RequestMessage}");
|
||
Console.WriteLine($"==5===请求响应失败,返回内容Content: {responseBody}");
|
||
throw new HttpRequestException($"请求发送失败: {responseBody}");
|
||
}
|
||
// 读取并返回响应内容
|
||
return responseBody;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 处理HTTP请求异常。
|
||
/// </summary>
|
||
/// <param name="exception">捕获的HttpRequestException异常。</param>
|
||
private void HandleHttpRequestException(HttpRequestException exception)
|
||
{
|
||
Console.WriteLine("exception" + 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}");
|
||
// 可以在这里添加日志记录或其他处理逻辑
|
||
}
|
||
}
|
||
}
|