chore: 初始化平芝126KV总装线 WebApi

This commit is contained in:
yexingqiang
2026-06-08 17:19:25 +08:00
commit 437c251f58
126 changed files with 5439 additions and 0 deletions

View File

@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebApi
{
public class BusinessController
{
}
}

25
WebApi/Helpers/Gl.cs Normal file
View File

@@ -0,0 +1,25 @@
using System;
namespace WebApi.Helpers
{
/// <summary>
/// 全局变量类
/// </summary>
public class Gl
{
/// <summary>
/// SQL Server连接状态
/// </summary>
public static bool OnLine_Sql { get; set; } = false;
/// <summary>
/// AGV连接状态
/// </summary>
public static bool OnLine_AGV { get; set; } = false;
/// <summary>
/// MQTT连接状态
/// </summary>
public static bool OnLine_MQTT { get; set; } = false;
}
}

View File

@@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace WebApi.Helpers
{
public class ValidationHelper
{
/// <summary>
/// 验证对象的必填字段
/// </summary>
/// <typeparam name="T">要验证的对象类型</typeparam>
/// <param name="obj">要验证的对象</param>
/// <param name="errorMessage">错误信息</param>
/// <returns>验证是否通过</returns>
public static bool ValidateRequired<T>(T obj, out string errorMessage)
{
errorMessage = string.Empty;
if (obj == null)
{
errorMessage = "对象不能为空";
return false;
}
var properties = typeof(T).GetProperties();
foreach (var prop in properties)
{
var value = prop.GetValue(obj);
if (value == null)
{
errorMessage = $"【{prop.Name}不能为空】";
return false;
}
//else if (prop.PropertyType == typeof(int) && (int)value == 0)
//{
// errorMessage = $"【{prop.Name}不能为0】";
// return false;
//}
else if (prop.PropertyType == typeof(string) && string.IsNullOrEmpty((string)value))
{
errorMessage = $"【{prop.Name}不能为空】";
return false;
}
else if (prop.PropertyType == typeof(object) && (object)value == null)
{
errorMessage = $"【{prop.Name}不能为空】";
return false;
}
}
return true;
}
/// <summary>
/// 验证对象的指定字段
/// </summary>
/// <typeparam name="T">要验证的对象类型</typeparam>
/// <param name="obj">要验证的对象</param>
/// <param name="propertyNames">要验证的属性名列表</param>
/// <param name="errorMessage">错误信息</param>
/// <returns>验证是否通过</returns>
public static bool ValidateProperties<T>(T obj, string[] propertyNames, out string errorMessage)
{
errorMessage = string.Empty;
if (obj == null)
{
errorMessage = "对象不能为空";
return false;
}
foreach (var propName in propertyNames)
{
var prop = typeof(T).GetProperty(propName);
if (prop == null) continue;
var value = prop.GetValue(obj);
if (value == null)
{
errorMessage = $"【{propName}不能为空】";
return false;
}
//else if (prop.PropertyType == typeof(int) && (int)value == 0)
//{
// errorMessage = $"【{propName}不能为0】";
// return false;
//}
else if (prop.PropertyType == typeof(string) && string.IsNullOrEmpty((string)value))
{
errorMessage = $"【{propName}不能为空】";
return false;
}
}
return true;
}
}
}

277
WebApi/IFileController.cs Normal file
View File

@@ -0,0 +1,277 @@
using System.Net.Http;
using System.Net;
using System.Web.Http;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System;
/////http://127.0.0.1:9981/api/file/browse
/// <summary>
///
/// </summary>
namespace WebApi
{
/// <summary>
///
/// </summary>
[RoutePrefix("api/file")]
public class IFileController : ApiController
{
// 基础路径配置
private readonly string _basePath = @"D:\项目文件";
/// <summary>
/// 请求DTO
/// </summary>
public class FileRequestDto
{
public string RelativePath { get; set; } = "";
}
/// <summary>
/// 浏览文件或文件夹,前端传相对路径,返回文件夹内容或文件流(图片等可预览)
/// </summary>
[HttpPost]
[Route("browse")]
public IHttpActionResult BrowsePath([FromBody] FileRequestDto request)
{
try
{
if (request == null)
request = new FileRequestDto();
if (string.IsNullOrEmpty(request.RelativePath) || request.RelativePath == "/")
{
request.RelativePath = "";
}
string fullPath = Path.Combine(_basePath, request.RelativePath.Replace('/', Path.DirectorySeparatorChar));
if (!IsPathSafe(fullPath))
{
return Ok(new { success = false, message = "无效的路径" });
}
if (!Directory.Exists(fullPath) && !System.IO.File.Exists(fullPath))
{
return Ok(new { success = false, message = "路径不存在" });
}
if (System.IO.File.Exists(fullPath))
{
return GetFilePreview(fullPath, request.RelativePath);
}
if (Directory.Exists(fullPath))
{
return GetDirectoryContents(fullPath, request.RelativePath);
}
return Ok(new { success = false, message = "路径不存在" });
}
catch (Exception ex)
{
return Ok(new { success = false, message = $"服务器错误: {ex.Message}" });
}
}
/// <summary>
/// 获取文件预览数据(图片/文本base64前端可直接预览
/// </summary>
private IHttpActionResult GetFilePreview(string fullPath, string relativePath)
{
try
{
var fileInfo = new FileInfo(fullPath);
var extension = fileInfo.Extension.ToLowerInvariant();
var previewable = IsPreviewableFile(extension);
var contentType = GetContentType(fileInfo.Name);
bool tooLarge = fileInfo.Length > 10 * 1024 * 1024; // 10MB限制
string base64String = null;
string dataUrl = null;
bool canPreview = previewable && !tooLarge;
if (canPreview)
{
var fileBytes = System.IO.File.ReadAllBytes(fullPath);
base64String = Convert.ToBase64String(fileBytes);
dataUrl = $"data:{contentType};base64,{base64String}";
}
var result = new
{
success = true,
type = "file",
path = relativePath,
name = fileInfo.Name,
size = fileInfo.Length,
extension = fileInfo.Extension,
contentType = contentType,
isPreviewable = canPreview,
base64Data = base64String,
dataUrl = dataUrl,
created = fileInfo.CreationTime,
modified = fileInfo.LastWriteTime,
message = tooLarge ? "文件过大,无法预览,可下载" : null
};
return Ok(result);
}
catch (Exception ex)
{
return Ok(new { success = false, message = $"获取文件预览失败: {ex.Message}" });
}
}
/// <summary>
/// 判断文件是否可预览
/// </summary>
private bool IsPreviewableFile(string extension)
{
var previewableExtensions = new[]
{
".bmp", ".jpg", ".jpeg", ".png", ".gif", ".tiff", ".tif", ".webp",
".txt", ".json", ".xml", ".csv", ".log", ".md"
};
return previewableExtensions.Contains(extension);
}
/// <summary>
/// 安全检查:确保路径在基础目录内,防止路径遍历攻击
/// </summary>
private bool IsPathSafe(string fullPath)
{
try
{
var basePath = Path.GetFullPath(_basePath);
var requestedPath = Path.GetFullPath(fullPath);
return requestedPath.StartsWith(basePath, StringComparison.OrdinalIgnoreCase);
}
catch
{
return false;
}
}
/// <summary>
/// 根据文件扩展名获取MIME类型兼容C# 7.3
/// </summary>
private string GetContentType(string fileName)
{
var extension = Path.GetExtension(fileName).ToLowerInvariant();
if (extension == ".bmp") return "image/bmp";
if (extension == ".jpg" || extension == ".jpeg") return "image/jpeg";
if (extension == ".png") return "image/png";
if (extension == ".gif") return "image/gif";
if (extension == ".tiff" || extension == ".tif") return "image/tiff";
if (extension == ".webp") return "image/webp";
if (extension == ".pdf") return "application/pdf";
if (extension == ".txt") return "text/plain";
if (extension == ".json") return "application/json";
if (extension == ".xml") return "application/xml";
if (extension == ".csv") return "text/csv";
if (extension == ".md") return "text/markdown";
if (extension == ".log") return "text/plain";
if (extension == ".zip") return "application/zip";
if (extension == ".rar") return "application/x-rar-compressed";
return "application/octet-stream";
}
private IHttpActionResult GetDirectoryContents(string fullPath, string relativePath)
{
try
{
var items = new List<object>();
var directories = Directory.GetDirectories(fullPath);
foreach (var dir in directories)
{
var dirInfo = new DirectoryInfo(dir);
var subPath = string.IsNullOrEmpty(relativePath)
? dirInfo.Name
: $"{relativePath}/{dirInfo.Name}";
items.Add(new
{
name = dirInfo.Name,
type = "directory",
path = subPath,
created = dirInfo.CreationTime,
modified = dirInfo.LastWriteTime,
isPreviewable = false
});
}
var files = Directory.GetFiles(fullPath);
foreach (var file in files)
{
var fileInfo = new FileInfo(file);
var filePath = string.IsNullOrEmpty(relativePath)
? fileInfo.Name
: $"{relativePath}/{fileInfo.Name}";
var extension = fileInfo.Extension.ToLowerInvariant();
items.Add(new
{
name = fileInfo.Name,
type = "file",
path = filePath,
size = fileInfo.Length,
extension = fileInfo.Extension,
created = fileInfo.CreationTime,
modified = fileInfo.LastWriteTime,
isPreviewable = IsPreviewableFile(extension),
contentType = GetContentType(fileInfo.Name)
});
}
var result = new
{
success = true,
type = "directory",
path = relativePath,
items = items.OrderBy(x => ((dynamic)x).type == "directory" ? 0 : 1)
.ThenBy(x => ((dynamic)x).name)
.ToList()
};
return Ok(result);
}
catch (Exception ex)
{
return Ok(new { success = false, message = $"读取目录失败: {ex.Message}" });
}
}
[HttpPost]
[Route("download")]
public IHttpActionResult DownloadFile([FromBody] FileRequestDto request)
{
try
{
if (request == null || string.IsNullOrEmpty(request.RelativePath))
return Ok(new { success = false, message = "文件路径不能为空" });
string fullPath = Path.Combine(_basePath, request.RelativePath.Replace('/', Path.DirectorySeparatorChar));
if (!IsPathSafe(fullPath) || !System.IO.File.Exists(fullPath))
return Ok(new { success = false, message = "文件不存在" });
var fileInfo = new FileInfo(fullPath);
var contentType = GetContentType(fileInfo.Name);
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
};
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = fileInfo.Name
};
return ResponseMessage(response);
}
catch (Exception ex)
{
return Ok(new { success = false, message = $"下载文件失败: {ex.Message}" });
}
}
}
}

View File

@@ -0,0 +1,81 @@
using System.Net.Http;
using System.Text;
using System.Web.Http;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
/////http://127.0.0.1:9981/api/IOrder/InsertOrder
/// <summary>
///
/// </summary>
namespace WebApi
{
/// <summary>
///
/// </summary>
[RoutePrefix("api/imes")]
public class imesController : ApiController
{
readonly string headUrl = "api/imes/";
[HttpPost]
public HttpResponseMessage TestPost([FromBody] JObject jobj)
{
if (jobj == null) jobj = new JObject();
return new HttpResponseMessage
{
Content = new StringContent(ServerController.TestPost(headUrl + System.Reflection.MethodBase.GetCurrentMethod().Name, jobj.ToString()), Encoding.GetEncoding("UTF-8"), "application/json")
};
}
/// <summary>
/// WEB发送请求给WEB API 注意 这是异步操作
/// </summary>
/// <param name="jobj"></param>
/// <returns></returns>
[HttpPost]
public async Task<HttpResponseMessage> MES_To_AGV_From_WEB([FromBody] JObject jobj)
{
if (jobj == null) jobj = new JObject();
var result = await ServerController.MES_To_AGV_From_WEB(headUrl + "MES_To_AGV_From_WEB", jobj.ToString());
return new HttpResponseMessage
{
Content = new StringContent(result, Encoding.GetEncoding("UTF-8"), "application/json")
};
}
/// <summary>
/// WEB发送请求给WEB API 注意 这是异步操作
/// 测试版
/// </summary>
/// <param name="jobj"></param>
/// <returns></returns>
[HttpPost]
public async Task<HttpResponseMessage> MES_To_AGV_From_WEB_Test([FromBody] JObject jobj)
{
if (jobj == null) jobj = new JObject();
var result = await ServerController.MES_To_AGV_From_WEB_Test(headUrl + "MES_To_AGV_From_WEB_Test", jobj.ToString());
return new HttpResponseMessage
{
Content = new StringContent(result, Encoding.GetEncoding("UTF-8"), "application/json")
};
}
/// <summary>
/// AGV与MES站点交互
/// </summary>
/// <param name="jobj"></param>
/// <returns></returns>
[HttpPost]
public async Task<HttpResponseMessage> AGV_To_MES_AgvPass([FromBody] JObject jobj)
{
if (jobj == null) jobj = new JObject();
var result = await ServerController.AGV_To_MES_AgvPass(headUrl + "AGV_To_MES_AgvPass", jobj.ToString());
return new HttpResponseMessage
{
Content = new StringContent(result, Encoding.GetEncoding("UTF-8"), "application/json")
};
}
}
}

142
WebApi/InitServer.cs Normal file
View File

@@ -0,0 +1,142 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Http.SelfHost;
namespace WebApi
{
/// <summary>
///
/// </summary>
public class InitServer
{
/// <summary>
///
/// </summary>
HttpSelfHostConfiguration config = null;
/// <summary>
///
/// </summary>
HttpSelfHostServer server = null;
/// <summary>
///
/// </summary>
/// <param name="port"></param>
public InitServer(int port)
{
config = new HttpSelfHostConfiguration($"http://0.0.0.0:{port}");
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
config.MapHttpAttributeRoutes();
//config.Routes.MapHttpRoute(
// name: "DefaultApi",
// routeTemplate: "api/{controller}/{id}",
// defaults: new { id = RouteParameter.Optional }
//);
// 自定义路由匹配到action
config.Routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
server = new HttpSelfHostServer(config);
server.OpenAsync().Wait();
}
public void Close()
{
server.CloseAsync();
}
/// <summary>
///
/// </summary>
public class JsonContentNegotiator : IContentNegotiator
{
/// <summary>
///
/// </summary>
private readonly JsonMediaTypeFormatter _jsonFormatter;
/// <summary>
///
/// </summary>
/// <param name="formatter"></param>
public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
{
_jsonFormatter = formatter;
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="request"></param>
/// <param name="formatters"></param>
/// <returns></returns>
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
{
var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
return result;
}
public static string Postring1(string url, string token, Dictionary<string, string> dic)
{
string results = "";
//url = "http://172.16.22.15:8000/" + url;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.Headers.Add("Authorization", "Bearer " + token);
StringBuilder builder = new StringBuilder();
int i = 0;
foreach (var item in dic)
{
if (i > 0)
builder.Append("&");
builder.AppendFormat("{0}={1}", item.Key, item.Value);
i++;
}
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
req.ContentLength = data.Length;
try
{
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
results = reader.ReadToEnd();
}
return results;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return e.Message;
throw;
}
}
}
}
}

View File

@@ -0,0 +1,33 @@
using System;
namespace WebApi.Models
{
public class AGV_To_MES_AgvArrive_Req
{
/// <summary>
/// 任务号 唯一ID
/// </summary>
public string taskId
{
get;
set;
}
/// <summary>
/// 工位号
/// </summary>
public string station
{
get;
set;
}
/// <summary>
/// AGV编号
/// </summary>
public int agvNum
{
get;
set;
}
}
}

View File

@@ -0,0 +1,89 @@
using System;
namespace WebApi.Models
{
public class AGV_To_MES_AgvMateria_Req
{
/// <summary>
/// 任务号 唯一ID
/// </summary>
public string taskId
{
get;
set;
}
/// <summary>
/// 客户端 固定值agv
/// </summary>
public string clientId
{
get;
set;
}
/// <summary>
/// 任务类型 0叫料1送料2叫空托3送空托4点对点5退料
/// </summary>
public int taskType
{
get;
set;
}
/// <summary>
/// 任务状态 3任务取消 21取货完成 23 放完
/// </summary>
public int status
{
get;
set;
}
/// <summary>
/// 取料点 taskType为134时必填
/// </summary>
public string pickStock
{
get;
set;
}
/// <summary>
/// 放料点 taskType为024时必填
/// </summary>
public string dropStock
{
get;
set;
}
/// <summary>
/// 托盘号
/// </summary>
public string palletId
{
get;
set;
}
/// <summary>
/// 物料号 物料编码(叫料时必填)
/// </summary>
public string materialId
{
get;
set;
}
/// <summary>
/// 需求数量
/// </summary>
public int requireNum
{
get;
set;
}
/// <summary>
/// 下发时间
/// </summary>
public string createTime
{
get;
set;
}
}
}

View File

@@ -0,0 +1,65 @@
using System;
namespace WebApi.Models
{
public class AGV_To_MES_AgvPass_Req
{
/// <summary>
/// 任务号 唯一ID
/// </summary>
public string taskId
{
get;
set;
}
/// <summary>
/// 工位号
/// </summary>
public string station
{
get;
set;
}
/// <summary>
/// 0到位1离开
/// </summary>
public int type
{
get;
set;
}
/// <summary>
/// AGV编号
/// </summary>
public int agvNum
{
get;
set;
}
/// <summary>
/// 总成编号
/// </summary>
public string EngineNo
{
get;
set;
}
/// <summary>
/// 订单号
/// </summary>
public string OrderNo
{
get;
set;
}
/// <summary>
/// 机型号
/// </summary>
public string SortNo
{
get;
set;
}
}
}

View File

@@ -0,0 +1,31 @@
namespace WebApi.Models
{
public class msgResHeader
{
/// <summary>
/// 返回结果 bool
/// </summary>
public bool Result
{
get;
set;
}
/// <summary>
/// 返回消息
/// </summary>
public string ErrMsg
{
get;
set;
}
/// <summary>
/// 返回结果集
/// </summary>
public object Data
{
get;
set;
}
}
}

23
WebApi/Models/test.cs Normal file
View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebApi.Models
{
public class test
{
public string msg
{
get;
set;
}
public int code
{
get;
set;
}
}
}

418
WebApi/ServerController.cs Normal file
View File

@@ -0,0 +1,418 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using WebApi.Models;
using WebApi.Helpers;
using System.Reflection;
using Logger;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace WebApi
{
public class ServerController
{
private static readonly HttpClient httpClient;
public static event Action<string> ShowMsg; // 记录日志事件
static ServerController()
{
httpClient = new HttpClient();
httpClient.Timeout = TimeSpan.FromSeconds(20); // 设置超时时间为20秒
}
/// <summary>
/// UUID生成
/// </summary>
/// <returns></returns>
public static string UuidUtil()
{
string result = Guid.NewGuid().ToString();
return result;
}
public static int SaveWebApiReqLogo(string url, string JSON)
{
int AID = -1;
try
{
//存储日志
var CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
var param = new Dictionary<string, Object>{
{ "接口地址", url },
{ "接口类型", 2 },
{ "请求内容", JSON },
{ "请求时间", CreateTime }
};
SqlServer.ExecuteProcedure("接口_IOT接口交互日志_请求记录", param, out DataTable dt, out string err);
if (dt.Rows.Count > 0)
{
AID = Convert.ToInt32(dt.Rows[0]["AID"]);
}
}
catch (Exception ex)
{
Log.FunError(ex, MethodBase.GetCurrentMethod().Name);
}
return AID;
}
public static int SaveWebApiResLogo(int AID, string JSON)
{
try
{
//new SqlParameter("@AID",AID),
//new SqlParameter("@响应时间",CreateTime),
//new SqlParameter("@响应内容",JsonConvert.SerializeObject(result))
//存储日志
var CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
var param = new Dictionary<string, Object>{
{ "AID", AID },
{ "响应时间", CreateTime },
{ "响应内容", JSON },
};
SqlServer.ExecuteProcedure("接口_IOT接口交互日志_响应记录", param, out DataTable dt, out string err);
if (dt.Rows.Count > 0)
{
AID = Convert.ToInt32(dt.Rows[0]["AID"]);
}
}
catch (Exception ex)
{
Log.FunError(ex, MethodBase.GetCurrentMethod().Name);
}
return AID;
}
/// <summary>
/// 测试标准接口方法
/// </summary>
/// <param name="url"></param>
/// <param name="str"></param>
/// <returns></returns>
public static string TestPost(string url, string json)
{
var result = new msgResHeader();
//result.taskId = UuidUtil();
result.Result = false;
result.ErrMsg = "";
result.Data = "";
string errorMessage = "";
int AID = -1;
try
{
AID = SaveWebApiReqLogo(url, json);
// 解析订单内容,存储数据库,根据实际业务来写
test personnelBaseData = JsonConvert.DeserializeObject<test>(json);
ShowMsg?.Invoke("【" + url + "】code" + personnelBaseData.code + ",msg:" + personnelBaseData.msg);
//result.msg = errorMessage;
AID = SaveWebApiResLogo(AID, JsonConvert.SerializeObject(result));
}
catch (Exception err)
{
result.Result = false;
result.ErrMsg = err.Message;
result.Data = "ERROR";
Log.FunError(err, MethodBase.GetCurrentMethod().Name);
}
return JsonConvert.SerializeObject(result);
}
/// <summary>
/// 前端对AGV通用的接口转发
/// </summary>
/// <param name="url"></param>
/// <param name="str"></param>
/// <returns></returns>
public static async Task<string> MES_To_AGV_From_WEB(string url, string json)
{
var result = new msgResHeader();
result.Result = false;
result.ErrMsg = "";
result.Data = "";
string errorMessage = "";
int AID = -1;
try
{
// 显示一下接口日志
ShowMsg?.Invoke("Receive【" + url + "】" + json);
AID = SaveWebApiReqLogo(url, json);
MES_To_AGV_From_WEB_Req personnelBaseData = JsonConvert.DeserializeObject<MES_To_AGV_From_WEB_Req>(json);
// 验证必填字段
if (!ValidationHelper.ValidateRequired(personnelBaseData, out errorMessage))
{
ShowMsg?.Invoke($"****************{errorMessage}");
result.ErrMsg = errorMessage;
return JsonConvert.SerializeObject(result);
}
string AGVApiBaseUrl = Tools.AppConfigManage.ReadConfig("AGVApiBaseUrl");
string AGVIP = Tools.AppConfigManage.ReadConfig("AGVIP");
string AGVApiUrl = "http://" + AGVIP + AGVApiBaseUrl + personnelBaseData.url;
// 发送POST请求
var content = new StringContent(
JsonConvert.SerializeObject(personnelBaseData.data),
Encoding.UTF8,
"application/json"
);
var response = await httpClient.PostAsync(AGVApiUrl, content);
var responseContent = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
result.Result = true;
result.Data = responseContent;
}
else
{
result.Result = false;
result.ErrMsg = $"请求失败: {response.StatusCode} - {responseContent}";
}
AID = SaveWebApiResLogo(AID, JsonConvert.SerializeObject(result));
}
catch (TaskCanceledException ex)
{
if (!ex.CancellationToken.IsCancellationRequested)
{
ShowMsg?.Invoke("请求超时,请检查目标服务是否可达或响应过慢!");
result.ErrMsg = "请求超时,请检查目标服务是否可达或响应过慢!";
}
else
{
ShowMsg?.Invoke("请求被主动取消!");
result.ErrMsg = "请求被主动取消!";
}
result.Data = "ERROR";
Log.FunError(ex, MethodBase.GetCurrentMethod().Name);
}
catch (Exception err)
{
result.Result = false;
result.ErrMsg = err.Message;
result.Data = "ERROR";
Log.FunError(err, MethodBase.GetCurrentMethod().Name);
}
return JsonConvert.SerializeObject(result);
}
/// <summary>
/// 前端对AGV通用的接口转发
/// 测试版
/// </summary>
/// <param name="url"></param>
/// <param name="str"></param>
/// <returns></returns>
public static async Task<string> MES_To_AGV_From_WEB_Test(string url, string json)
{
var result = new msgResHeader();
result.Result = false;
result.ErrMsg = "";
result.Data = "";
string errorMessage = "";
int AID = -1;
try
{
// 显示一下接口日志
ShowMsg?.Invoke("Receive【" + url + "】" + json);
AID = SaveWebApiReqLogo(url, json);
var result2 = new msgResHeader();
result2.Result = true;
result2.ErrMsg = "";
result2.Data = "";
MES_To_AGV_From_WEB_Req personnelBaseData = JsonConvert.DeserializeObject<MES_To_AGV_From_WEB_Req>(json);
// 验证必填字段
if (!ValidationHelper.ValidateRequired(personnelBaseData, out errorMessage))
{
ShowMsg?.Invoke($"****************{errorMessage}");
result.ErrMsg = errorMessage;
return JsonConvert.SerializeObject(result);
}
// 手动模拟
// 接口1 库区列表查询 返回固定JSON数据
if(personnelBaseData.url == "getPartitionList")
{
var partitionList = new List<object>
{
new { PartitionCode = "1", PartitionName = "隔离开关操作试验区" },
new { PartitionCode = "2", PartitionName = "断路器线边缓存位" },
new { PartitionCode = "3", PartitionName = "CT装配区" },
new { PartitionCode = "4", PartitionName = "断路器下线" },
new { PartitionCode = "5", PartitionName = "OP30产线工位" },
new { PartitionCode = "6", PartitionName = "线边缓存库" },
new { PartitionCode = "7", PartitionName = "断路器试验区" },
new { PartitionCode = "8", PartitionName = "隔离开关安装操作缓存区" },
new { PartitionCode = "9", PartitionName = "隔离开关下线" },
new { PartitionCode = "10", PartitionName = "断路器缓存区" },
new { PartitionCode = "11", PartitionName = "OP20产线工位" },
new { PartitionCode = "12", PartitionName = "OP10产线工位" }
};
result.Result = true;
result2.Data = partitionList;
result.Data = JsonConvert.SerializeObject(result2);
}
// 接口2 库位列表查询 返回固定JSON数据
if(personnelBaseData.url == "getStockList")
{
var stockList = new List<object>
{
// StockCode 库位编号
// StockName 库位名称
// StockStatus 满料状态 bool
// PalletCode 托盘编号
// EngineNo 产品编号
// SortNo 产品型号
// TaskId 任务号
new { StockCode = "6", StockName = "工位线边缓存位1", StockStatus = true, PalletCode = "pallTestCode1", EngineNo = "GCBTest01", SortNo = "P7223814G003", TaskId = "12312" },
new { StockCode = "16", StockName = "工位线边缓存位2", StockStatus = true, PalletCode = "pallTestCode2", EngineNo = "CTTest01-1", SortNo = "P7223363G001", TaskId = (string)null },
new { StockCode = "30", StockName = "工位线边缓存位3", StockStatus = false, PalletCode = "pallTestCode3", EngineNo = (string)null, SortNo = (string)null, TaskId = (string)null },
new { StockCode = "2", StockName = "工位线边缓存位4", StockStatus = false, PalletCode = (string)null, EngineNo = (string)null, SortNo = (string)null, TaskId = (string)null },
};
result.Result = true;
result2.Data = stockList;
result.Data = JsonConvert.SerializeObject(result2);
}
// 接口3 更新库位信息
if (personnelBaseData.url == "updateStockInfo")
{
result.Result = true;
result.Data = JsonConvert.SerializeObject(result2);
}
// 接口4 创建送料任务
if (personnelBaseData.url == "createTask")
{
result.Result = true;
result.Data = JsonConvert.SerializeObject(result2);
}
AID = SaveWebApiResLogo(AID, JsonConvert.SerializeObject(result));
}
catch (TaskCanceledException ex)
{
if (!ex.CancellationToken.IsCancellationRequested)
{
ShowMsg?.Invoke("请求超时,请检查目标服务是否可达或响应过慢!");
result.ErrMsg = "请求超时,请检查目标服务是否可达或响应过慢!";
}
else
{
ShowMsg?.Invoke("请求被主动取消!");
result.ErrMsg = "请求被主动取消!";
}
result.Data = "ERROR";
Log.FunError(ex, MethodBase.GetCurrentMethod().Name);
}
catch (Exception err)
{
result.Result = false;
result.ErrMsg = err.Message;
result.Data = "ERROR";
Log.FunError(err, MethodBase.GetCurrentMethod().Name);
}
return JsonConvert.SerializeObject(result);
}
/// <summary>
/// AGV到位,离开
/// </summary>
/// <param name="url"></param>
/// <param name="str"></param>
/// <returns></returns>
public static async Task<string> AGV_To_MES_AgvPass(string url, string json)
{
var result = new msgResHeader();
result.Result = false;
result.ErrMsg = "";
result.Data = "";
string errorMessage = "";
int AID = -1;
try
{
// 显示一下接口日志
ShowMsg?.Invoke("Receive【" + url + "】" + json);
AID = SaveWebApiReqLogo(url, json);
// 解析订单内容,存储数据库,根据实际业务来写
AGV_To_MES_AgvPass_Req personnelBaseData = JsonConvert.DeserializeObject<AGV_To_MES_AgvPass_Req>(json);
// 验证必填字段
if (!ValidationHelper.ValidateRequired(personnelBaseData, out errorMessage))
{
ShowMsg?.Invoke($"****************{errorMessage}");
result.ErrMsg = errorMessage;
return JsonConvert.SerializeObject(result);
}
int workOverType = 0;
if (personnelBaseData.type == 0)
{
workOverType = 1;
}
else if (personnelBaseData.type == 1)
{
workOverType = 3;
}
else
{
ShowMsg?.Invoke($"****************未识别的type{workOverType}");
result.ErrMsg = $"未识别的Type{workOverType}";
return JsonConvert.SerializeObject(result);
}
var param = new Dictionary<string, Object>{
{ "工位号", personnelBaseData.station },
{ "任务编号", personnelBaseData.taskId },
{ "工件编号", personnelBaseData.EngineNo },
{ "type", workOverType},
};
SqlServer.ExecuteProcedure("PTCHV_AGV_进离站", param, out DataTable dt, out errorMessage);
// 验证必填字段
if (errorMessage.Length > 0)
{
ShowMsg?.Invoke($"****************{errorMessage}");
result.ErrMsg = errorMessage;
return JsonConvert.SerializeObject(result);
}
await MqttServer.SendMqttMessageToOp(personnelBaseData.station, "AGVStatus", workOverType.ToString());
result.Result = true;
AID = SaveWebApiResLogo(AID, JsonConvert.SerializeObject(result));
}
catch (Exception err)
{
result.Result = false;
result.ErrMsg = err.Message;
result.Data = "ERROR";
Log.FunError(err, MethodBase.GetCurrentMethod().Name);
}
return JsonConvert.SerializeObject(result);
}
}
}