add - 物料信息同步功能完成,待测试,配方信息待完善接口文档

dep_wangsr
SoulStar 2 months ago
parent f93bae5f52
commit f7a39845b1

@ -1753,6 +1753,11 @@
起始页编号
</summary>
</member>
<member name="P:Admin.Core.Api.PLTBusiness.Entity.MaterialRecordListItem.id">
<summary>
物料id
</summary>
</member>
<member name="P:Admin.Core.Api.PLTBusiness.Entity.MaterialRecordListItem.name">
<summary>
物料名称
@ -1798,6 +1803,22 @@
Token失效时间
</summary>
</member>
<member name="M:Admin.Core.Api.PLTBusiness.HttpService.GetMaterialDataPageList">
<summary>
分页拉取所有Mes物料信息
</summary>
<returns></returns>
</member>
<member name="M:Admin.Core.Api.PLTBusiness.HttpService.GetToken">
<summary>
获取Token
</summary>
</member>
<member name="M:Admin.Core.Api.PLTBusiness.HttpService.RefreshToken">
<summary>
刷新Token
</summary>
</member>
<member name="M:Admin.Core.Api.PLTBusiness.HttpService.PostAsync(System.String,System.String,System.String,System.String,System.Collections.Generic.Dictionary{System.String,System.String},System.Int32)">
<summary>
发起POST异步请求

@ -250,7 +250,7 @@ namespace Admin.Core.Api
{
try
{
var result = await _xl_materialService.xlInsertMaterial(materialCode, materialName, isEnable, createDateTime);
var result = await _xl_materialService.xlInsertMaterial(Guid.NewGuid().ToString("N"), materialCode, materialName, isEnable, createDateTime);
if (result)
{
return Success(result);

@ -6,7 +6,7 @@
<appender name="ErrorLog" type="log4net.Appender.RollingFileAppender">
<!--不加utf-8编码格式中文字符将显示成乱码-->
<param name="Encoding" value="utf-8" />
<file value="E:\log\"/>
<file value="../../../Log/"/>
<appendToFile value="true" />
<rollingStyle value="Date" />
<!--日期的格式,每天换一个文件记录,如不设置则永远只记录一天的日志,需设置-->
@ -26,8 +26,6 @@
</appender>
<!--Error-->
<!--Info-->
<appender name="InfoLog" type="log4net.Appender.RollingFileAppender">
<!--不加utf-8编码格式中文字符将显示成乱码-->
@ -53,6 +51,15 @@
</appender>
<!--Info-->
<!--Console-->
<appender name="ConsoleLog" type="log4net.Appender.ConsoleAppender">
<!--布局(向用户显示最后经过格式化的输出信息)-->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date | %-5level | %message%newline" />
</layout>
</appender>
<!--Console-->
<root>
<!-- 控制级别由低到高ALL|DEBUG|INFO|WARN|ERROR|FATAL|OFF -->
<!-- 比如定义级别为INFO则INFO级别向下的级别比如DEBUG日志将不会被记录 -->
@ -61,5 +68,6 @@
<!-- 按日期切分日志文件,并将日期作为日志文件的名字 -->
<appender-ref ref="ErrorLog" />
<appender-ref ref="InfoLog" />
<appender-ref ref="ConsoleLog" />
</root>
</log4net>

@ -41,6 +41,10 @@ namespace Admin.Core.Api.PLTBusiness.Entity
public class MaterialRecordListItem
{
/// <summary>
/// 物料id
/// </summary>
public int id { get; set; }
/// <summary>
/// 物料名称
/// </summary>

@ -1,8 +1,12 @@
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;
@ -19,22 +23,17 @@ namespace Admin.Core.Api.PLTBusiness
public class HttpService : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly log4net.ILog log = LogManager.GetLogger(typeof(HttpService));
private string _token;
private readonly IServiceScopeFactory _scopeFactory;
private int _tokenExpirationTime;
private readonly IHttpClientFactory _httpClientFactory;
private Dictionary<string, string> _tokenDictionary = new Dictionary<string, string>()
{
{"authCode", "QT_XXX"},
{"appid", "q7cloud_XXX"},
{"secret", "f434eab8b9652524dc719e33f4ff255a45570XXX"}
};
private readonly string _host;
private string _host;
private string _token;
private readonly IHttpClientFactory _httpClientFactory;
private int _tokenExpirationTime = 0;
public HttpService(IHttpClientFactory httpClientFactory, IServiceScopeFactory scopeFactory)
{
@ -44,25 +43,128 @@ namespace Admin.Core.Api.PLTBusiness
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)
{
//执行任务
Console.WriteLine($"{DateTime.Now}");
//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);
}
await xlBusiness.InsertNewMaterialData(null);
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);
}
await Task.Delay(1000*10);
}
#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;
}
private async void GetToken()
#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);
@ -70,22 +172,63 @@ namespace Admin.Core.Api.PLTBusiness
ResponseRoot<TokenData> responseRoot = JsonSerializer.Deserialize<ResponseRoot<TokenData>>(tokenJson);
if (responseRoot == null)
{
Console.WriteLine("Token获取失败");
return;
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)
if (responseRoot.code != 200)
{
Console.WriteLine("ERROR 状态码:" + responseRoot.code);
return;
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)
{
Console.WriteLine("ERROR: " + ex.ToString());
log.Error("Token更新失败 ERROR: " + ex.ToString());
return false;
}
}
#endregion
#region HTTP操作
/// <summary>
/// 发起POST异步请求
/// </summary>
@ -136,8 +279,8 @@ namespace Admin.Core.Api.PLTBusiness
}
catch (Exception ex)
{
Console.WriteLine($"ERROR: {ex.ToString()} Time: {DateTime.Now}");
return string.Empty;
log.Error($"Post请求失败 URL{url} ERROR: {ex.ToString()} Time: {DateTime.Now}");
throw;
}
}
@ -182,8 +325,8 @@ namespace Admin.Core.Api.PLTBusiness
}
catch (Exception ex)
{
Console.WriteLine($"ERROR: {ex.ToString()} Time: {DateTime.Now}");
return string.Empty;
log.Error($"Get请求失败 URL{url} ERROR: {ex.ToString()} Time: {DateTime.Now}");
throw;
}
}
@ -217,14 +360,15 @@ namespace Admin.Core.Api.PLTBusiness
{
// 读取响应内容
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Response: {responseBody}");
log.Info($"Response: {responseBody}");
}
else
{
Console.WriteLine($"Error: {response.StatusCode}");
log.Error($"Error: {response.StatusCode}");
}
}
#endregion
#region 私有函数

@ -26,24 +26,49 @@ namespace Admin.Core.Api.PLTBusiness
_xl_materialService = xl_materialService;
}
/// <summary>
/// 向物料数据库中动态同步mes数据没有就插入不同就修改
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public async Task<bool> InsertNewMaterialData(List<MaterialRecordListItem> list)
{
List<xl_material> mlist = new List<xl_material>();
mlist = await _xl_materialService.xlMaterialList();
bool state = await _xl_materialService.xlUpdateMaterial("4cbdaa3913a54092bff72e09f13e633f"
, "123412421567"
, "更新213214测试测试"
, 1
, DateTime.Now);
//foreach (var mesItem in list)
//{
// foreach(var mItem in mlist)
// {
try
{
foreach (var mesMaterial in list)
{
// Step 3: 在B表中查询是否存在相同ID的记录
var material = await _xl_materialService.SelectXlMaterialById(mesMaterial.id.ToString());
// }
//}
return true;
if (material == null)
{
// Step 4: 如果B表中不存在该物料插入新物料
await _xl_materialService.xlInsertMaterial(
mesMaterial.id.ToString(),
mesMaterial.code, mesMaterial.name, mesMaterial.status,
Convert.ToDateTime(mesMaterial.createTime));
}
else
{
// Step 5: 如果B表中存在该物料且有更新更新物料信息
if (material.Material_code != mesMaterial.code ||
material.Material_name != mesMaterial.name ||
material.IsEnable != (mesMaterial.status == 1 ? "是" : "否") ||
material.CreateDateTime != Convert.ToDateTime(mesMaterial.createTime))
{
await _xl_materialService.xlUpdateMaterial(
mesMaterial.id.ToString(),
mesMaterial.code, mesMaterial.name, mesMaterial.status,
Convert.ToDateTime(mesMaterial.createTime));
}
}
}
return true;
}
catch (Exception ex)
{
throw;
}
}

@ -32,12 +32,31 @@ namespace Admin.Core.IService
Task<MessageModel<bool>> MaterialVerification(string barCode);
/// <summary>
/// 物料插入
/// </summary>
/// <param name="id"></param>
/// <param name="materialCode"></param>
/// <param name="materialName"></param>
/// <param name="isEnable"></param>
/// <param name="createDatetime"></param>
/// <returns></returns>
Task<bool> xlInsertMaterial(
string id,
string materialCode,
string materialName,
int isEnable,
DateTime createDatetime);
/// <summary>
/// 物料更新
/// </summary>
/// <param name="id"></param>
/// <param name="materialCode"></param>
/// <param name="materialName"></param>
/// <param name="isEnable"></param>
/// <param name="createDatetime"></param>
/// <returns></returns>
Task<bool> xlUpdateMaterial(
string id,
string materialCode,
@ -45,6 +64,17 @@ namespace Admin.Core.IService
int isEnable,
DateTime createDatetime);
/// <summary>
/// 物料查询
/// </summary>
/// <returns></returns>
Task<List<xl_material>> xlMaterialList();
/// <summary>
/// 根据ID查询
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
Task<xl_material> SelectXlMaterialById(string id);
}
}

@ -507,7 +507,7 @@ namespace Admin.Core.PlcServer
{
siemensS7Net.ReceiveTimeOut = 2000;
OperateResult<bool> read = await siemensS7Net.ReadBoolAsync(address);
log.Info($"心跳方法是否成功:{read.IsSuccess};反馈:{read.Message}");
//log.Info($"心跳方法是否成功:{read.IsSuccess};反馈:{read.Message}");
if (read.IsSuccess)
{
IsConnected = true;

@ -695,6 +695,7 @@ namespace Admin.Core.Service
/// <param name="productName"></param>
/// <returns></returns>
public async Task<bool> xlInsertMaterial(
string id,
string materialCode,
string materialName,
int isEnable,
@ -704,7 +705,7 @@ namespace Admin.Core.Service
{
xl_material xl_m = new xl_material()
{
ID = Guid.NewGuid().ToString("N"),
ID = id,
Material_code = materialCode,
Material_name = materialName,
CreateDateTime = createDatetime,
@ -728,7 +729,7 @@ namespace Admin.Core.Service
}
catch (Exception ex)
{
return false;
throw;
}
}
@ -768,7 +769,7 @@ namespace Admin.Core.Service
}
catch (Exception e)
{
return false;
throw;
}
}
@ -789,10 +790,26 @@ namespace Admin.Core.Service
}
catch (Exception ex)
{
return null;
throw;
}
}
/// <summary>
/// 根据ID查询物料信息
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public async Task<xl_material> SelectXlMaterialById(string id)
{
try
{
return await _xl_materialRepository.QueryByIdAsync(id);
}
catch (Exception ex)
{
throw;
}
}
}
}
Loading…
Cancel
Save