You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

397 lines
14 KiB
C#

using Admin.Core.Api.PLTBusiness.Entity;
using Admin.Core.Common;
using Admin.Core.IService;
using Admin.Core.PlcServer;
using Admin.Core.Service;
using log4net;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NPOI.HSSF.Record;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Policy;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace Admin.Core.Api.PLTBusiness
{
public class HttpService : BackgroundService
{
private readonly log4net.ILog log = LogManager.GetLogger(typeof(HttpService));
private readonly IServiceScopeFactory _scopeFactory;
private readonly IHttpClientFactory _httpClientFactory;
private readonly string _host;
private string _token;
private int _tokenExpirationTime = 0;
public HttpService(IHttpClientFactory httpClientFactory, IServiceScopeFactory scopeFactory)
{
_httpClientFactory = httpClientFactory;
_scopeFactory = scopeFactory;
}
protected async override Task ExecuteAsync(CancellationToken stoppingToken)
{
int second = 1000 * 10;
using var scope = _scopeFactory.CreateScope();
var services = scope.ServiceProvider;
var xlBusiness = services.GetService<XlBusiness>();
while (!stoppingToken.IsCancellationRequested)
{
//执行任务
//log.Info($"{DateTime.Now}");
if (_tokenExpirationTime == 0)
{
if (await GetToken())
{
log.Info("Token Get! Value:" + _token);
}
else
{
log.Error("Token Get Falied");
}
}
else if (_tokenExpirationTime <= 86400)
{
RefreshToken();
}
else
{
_tokenExpirationTime = _tokenExpirationTime - (second / 1000);
}
try
{
if (_token.IsNotEmptyOrNull())
{
await xlBusiness.InsertNewMaterialData(await GetMaterialDataPageList());
}
else
{
log.Error("No Token!!!");
}
}
catch (Exception ex)
{
log.Error("Error: " + ex);
}
await Task.Delay(second);
}
}
#region Mes信息拉取
/// <summary>
/// 分页拉取所有Mes物料信息
/// </summary>
/// <returns></returns>
private async Task<List<MaterialRecordListItem>> GetMaterialDataPageList()
{
int pageSize = 200;
int pageIndex = 0;
int pageCount = 1;
string orgCode = "Mesnac";
List<MaterialRecordListItem> allMaterials = new List<MaterialRecordListItem>();
Dictionary<string, object> _pageInfo = new Dictionary<string, object>()
{
{"pageIndex", 200},
{"pageSize", 0},
{"orgCode", "Mesnac"},
};
try
{
do
{
string body = JsonSerializer.Serialize(_pageInfo);
string materialJson = await PostAsync(_host + "/qtn/api/q7/com/inventory/page",
body, "application/json", "application/json",
new Dictionary<string, string> { { "token", _token } }, 10);
ResponseRoot<MaterialData> responseRoot = JsonSerializer.Deserialize<ResponseRoot<MaterialData>>(materialJson);
if (responseRoot == null)
{
log.Error("物料信息拉取失败!");
return null;
}
if (responseRoot.code != 200)
{
log.Error("ERROR 状态码:" + responseRoot.code);
return null;
}
pageCount = responseRoot.Data.pageCount;
pageIndex = responseRoot.Data.pageIndex;
allMaterials.AddRange(responseRoot.Data.recordList);
pageIndex = pageIndex + 1;
}
while (pageIndex < pageSize);
}
catch (Exception ex)
{
log.Error("Mes物料信息拉取失败 Error: " + ex);
return null;
}
return allMaterials;
}
#endregion
#region Token获取
/// <summary>
/// 获取Token
/// </summary>
private async Task<bool> GetToken()
{
Dictionary<string, string> _tokenDictionary = new Dictionary<string, string>()
{
{"authCode", "QT_XXX"},
{"appid", "q7cloud_XXX"},
{"secret", "f434eab8b9652524dc719e33f4ff255a45570XXX"}
};
try
{
string body = JsonSerializer.Serialize(_tokenDictionary);
string tokenJson = await PostAsync(_host + "/qtn/api/auth/token", body, "application/json", "application/json", null, 10);
ResponseRoot<TokenData> responseRoot = JsonSerializer.Deserialize<ResponseRoot<TokenData>>(tokenJson);
if (responseRoot == null)
{
log.Error("Token获取失败");
return false;
}
if (responseRoot.code != 200)
{
log.Error("ERROR 状态码:" + responseRoot.code);
return false;
}
_token = responseRoot.Data.token;
_tokenExpirationTime = responseRoot.Data.expiration;
log.Info("Token获取成功" + _token + "超时时间:" + _tokenExpirationTime);
return true;
}
catch (Exception ex)
{
log.Error("Token获取失败 ERROR: " + ex.ToString());
return false;
}
}
/// <summary>
/// 刷新Token
/// </summary>
private async Task<bool> RefreshToken()
{
try
{
string tokenJson = await PostAsync(_host + "/qtn/api/auth/token/refresh", ""
, "application/json", "application/x-www-form-urlencoded"
, new Dictionary<string, string>() { { "token", _token } }, 10);
ResponseRoot<TokenData> responseRoot = JsonSerializer.Deserialize<ResponseRoot<TokenData>>(tokenJson);
if (responseRoot == null)
{
log.Error("Token更新失败");
return false;
}
if (responseRoot.code != 200)
{
log.Error("ERROR 状态码:" + responseRoot.code);
return false;
}
_token = responseRoot.Data.token;
_tokenExpirationTime = responseRoot.Data.expiration;
log.Info("Token更新成功" + _token + "超时时间:" + _tokenExpirationTime);
return true;
}
catch (Exception ex)
{
log.Error("Token更新失败 ERROR: " + ex.ToString());
return false;
}
}
#endregion
#region HTTP操作
/// <summary>
/// 发起POST异步请求
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="body">POST提交的内容</param>
/// <param name="bodyMediaType">POST内容的媒体类型application/xml、application/json</param>
/// <param name="responseContentType">HTTP响应上的content-type内容头的值,如application/xml、application/json、application/text、application/x-www-form-urlencoded等</param>
/// <param name="headers">请求头信息</param>
/// <param name="timeOut">请求超时时间,单位秒</param>
/// <returns>返回string</returns>
private async Task<string> PostAsync(string url, string body,
string bodyMediaType = null,
string responseContentType = null,
Dictionary<string, string> headers = null,
int timeOut = 30)
{
try
{
var hostName = GetHostName(url);
using (HttpClient client = _httpClientFactory.CreateClient(hostName))
{
client.Timeout = TimeSpan.FromSeconds(timeOut);
if (headers?.Count > 0)
{
foreach (string key in headers.Keys)
{
client.DefaultRequestHeaders.Add(key, headers[key]);
}
}
StringContent content = new StringContent(body, System.Text.Encoding.UTF8, mediaType: bodyMediaType);
if (!string.IsNullOrWhiteSpace(responseContentType))
{
content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(responseContentType);
}
using (HttpResponseMessage response = await client.PostAsync(url, content))
{
if (response.IsSuccessStatusCode)
{
string responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
else
{
return string.Empty;
}
}
}
}
catch (Exception ex)
{
log.Error($"Post请求失败 URL{url} ERROR: {ex.ToString()} Time: {DateTime.Now}");
throw;
}
}
/// <summary>
/// 发起GET异步请求
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="url">请求地址</param>
/// <param name="headers">请求头信息</param>
/// <param name="timeOut">请求超时时间,单位秒</param>
/// <returns>返回string</returns>
private async Task<string> GetAsync(string url, Dictionary<string, string> headers = null, int timeOut = 30)
{
try
{
var hostName = GetHostName(url);
using (HttpClient client = _httpClientFactory.CreateClient(hostName))
{
client.Timeout = TimeSpan.FromSeconds(timeOut);
if (headers?.Count > 0)
{
foreach (string key in headers.Keys)
{
client.DefaultRequestHeaders.Add(key, headers[key]);
}
}
using (HttpResponseMessage response = await client.GetAsync(url))
{
if (response.IsSuccessStatusCode)
{
string responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
else
{
return string.Empty;
}
}
}
}
catch (Exception ex)
{
log.Error($"Get请求失败 URL{url} ERROR: {ex.ToString()} Time: {DateTime.Now}");
throw;
}
}
private async Task Post(string url, Dictionary<string, string> headers = null)
{
var hostName = GetHostName(url);
// 创建 HttpClient 实例
var client = _httpClientFactory.CreateClient(hostName);
// 定义要发送的对象
//var data = new
//{
// Name = "John Doe",
// Age = 30,
// Email = "john.doe@example.com"
//};
// 序列化对象为 JSON
var json = JsonSerializer.Serialize(headers);
// 创建 HttpContent设置内容为 JSON 格式
var content = new StringContent(json, Encoding.UTF8, "application/json");
// 发送 POST 请求
var response = await client.PostAsync(url, content);
// 检查响应状态码
if (response.IsSuccessStatusCode)
{
// 读取响应内容
var responseBody = await response.Content.ReadAsStringAsync();
log.Info($"Response: {responseBody}");
}
else
{
log.Error($"Error: {response.StatusCode}");
}
}
#endregion
#region 私有函数
/// <summary>
/// 获取请求的主机名
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private static string GetHostName(string url)
{
if (!string.IsNullOrWhiteSpace(url))
{
return url.Replace("https://", "").Replace("http://", "").Split('/')[0];
}
else
{
return "AnyHost";
}
}
#endregion
}
}