using Hanhe.iWCS.Common; using Hanhe.iWCS.MData; using Hanhe.iWCS.Model; using MongoDB.Bson; using MongoDB.Driver; using MongoDB.Driver.Builders; using Newtonsoft.Json; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using static Hanhe.iWCS.TaizhouGEMTwoProtocol.ApiHelper; using static Hanhe.iWCS.TaizhouGEMTwoProtocol.MESHelper; namespace Hanhe.iWCS.TaizhouGEMTwoProtocol { public class ERPService { /* * 变更优化操作: * * 注释内容: * PLCControl.SecondWeightInCache6 方法 * * **/ static WebApiHelper api = new WebApiHelper(); public const string ERPSwitch01 = "1";// ERP变更流程开关 public static List SendERPTaskType = Settings.SendERPTaskType.Split(',').ToList();//回报任务类型 public static List LoginInfo = Settings.LoginInfo.Split(',').ToList();// ERP登录接口传输信息 /// /// ERP物料下发接口 /// /// /// public static SimpleResult Item(ERPItemTable itemTable) { SimpleResult result = new SimpleResult { success = false}; // 查询中间表是否存在数据,如果存在,则进行更新;如果不存在,则获取当前【物料序号】,并进行累加插入数据 var query = Query.EQ("item_code", itemTable.item_code); var erpItemInfo = MongoDBSingleton.Instance.FindOne(query, "ERPItemTable"); if (erpItemInfo != null) { var update = Update.Set("item_name", itemTable.item_name).Set("item_spec", itemTable.item_spec) .Set("item_uom", itemTable.item_uom).Set("dateTime", DateTime.Now); MongoDBSingleton.Instance.Update(query, update, "ERPItemTable", MongoDB.Driver.UpdateFlags.None); result.success = true; } else { int itemNo = 1; // 获取最大序号的数据 var maxErpItemInfoList = MongoDBSingleton.Instance.FindAll("ERPItemTable"); if (maxErpItemInfoList.Count > 0) { var maxErpItemInfo = maxErpItemInfoList.OrderByDescending(it => it.item_no).First(); if (maxErpItemInfo != null) itemNo = maxErpItemInfo.item_no + 1; } MongoDBSingleton.Instance.Insert(new ERPItemTable { item_no = itemNo, item_code = itemTable.item_code, item_name = itemTable.item_name, item_spec = itemTable.item_spec, item_uom = itemTable.item_uom, dateTime = DateTime.Now }, "ERPItemTable"); result.success = true; } return result; } /// /// ERP员工信息下发接口 /// /// /// public static SimpleResult Employee(ERPEmployeeTable itemTable) { SimpleResult result = new SimpleResult { success = false }; // 查询中间表是否存在数据,如果存在,则进行更新;如果不存在,则获取当前【物料序号】,并进行累加插入数据 var query = Query.EQ("employee_id", itemTable.employee_id); var erpItemInfo = MongoDBSingleton.Instance.FindOne(query, "ERPEmployeeTable"); if (erpItemInfo != null) { var update = Update.Set("employee_name", itemTable.employee_name).Set("dateTime", DateTime.Now); MongoDBSingleton.Instance.Update(query, update, "ERPEmployeeTable", MongoDB.Driver.UpdateFlags.None); result.success = true; } else { int itemNo = 1; // 获取最大序号的数据 var maxErpItemInfoList = MongoDBSingleton.Instance.FindAll("ERPEmployeeTable"); if (maxErpItemInfoList.Count > 0) { var maxErpItemInfo = maxErpItemInfoList.OrderByDescending(it => it.item_no).First(); if (maxErpItemInfo != null) itemNo = maxErpItemInfo.item_no + 1; } MongoDBSingleton.Instance.Insert(new ERPEmployeeTable { item_no = itemNo, employee_id = itemTable.employee_id, employee_name = itemTable.employee_name, dateTime = DateTime.Now }, "ERPEmployeeTable"); result.success = true; } return result; } /// /// ERP物料中间表 /// public class ERPItemTable { public ObjectId _id { get; set; } /// /// 物料序号(唯一) /// public int item_no { get; set; } /// /// 物料编码(唯一) /// public string item_code { get; set; } /// /// 物料名称 /// public string item_name { get; set; } /// /// 规格型号 /// public string item_spec { get; set; } /// /// 单位 /// public string item_uom { get; set; } /// /// 操作时间 /// public DateTime dateTime { get; set; } } /// /// ERP员工信息中间表 /// public class ERPEmployeeTable { public ObjectId _id { get; set; } /// /// 物料序号(唯一) /// public int item_no { get; set; } /// /// 物料编码 /// public string item_code { get; set; } /// /// 物料名称 /// public string item_name { get; set; } /// /// 员工工号 /// public string employee_id { get; set; } /// /// 员工名称 /// public string employee_name { get; set; } /// /// 操作时间 /// public DateTime dateTime { get; set; } } public static void SendERPTaskInfo(TN_I_TASK_MST mst) { var sendERPTaskInfo = MongoDBSingleton.Instance.FindOne(Query.EQ("taskNo", mst.CN_S_TASK_NO), "SendErpTaskInfoTable"); if (sendERPTaskInfo == null) { //string timeStamp = ""; //if (mst.transportInfo.Count > 0) timeStamp = mst.transportInfo.First().itemPCode; MongoDBSingleton.Instance.Insert(new SendErpTaskInfoTable { taskNo = mst.CN_S_TASK_NO, timeStamp = mst.Ext2,// mst.CN_S_BATCH_NO dateTime = DateTime.Now.AddHours(8) }, "SendErpTaskInfoTable"); } else CMMLog.Error($"SendERPTaskInfo Error:当前任务号数据已存在,不允许插入 SendErpTaskInfoTable 记录表。任务号:{mst.CN_S_TASK_NO}"); } public class SendErpTaskInfoTable { public ObjectId _id { get; set; } /// /// 任务号(唯一) /// public string taskNo { get; set; } /// /// 时间戳-对应任务数据 CN_S_BATCH_NO 字段值 /// public string timeStamp { get; set; } public DateTime dateTime { get; set; } } /// /// 入库任务完成回报ERP信息 /// /// /// public static void SendERPTaskCompleteFunc() { var sendERPTaskInfoList = MongoDBSingleton.Instance.FindAll(); if (sendERPTaskInfoList.Count > 0) { // 先根据任务批次号字段获取时间戳中间表-TimeCuoInfoCom 数据,并进行后续调用,处理成功删除时间戳中间表-TimeCuoInfoCom 数据 sendERPTaskInfoList.ForEach(a => { bool result = ERPApiFuncTwo(a.timeStamp); if (result) { MongoDBSingleton.Instance.Remove(Query.EQ("_id", a._id), "SendErpTaskInfoTable", RemoveFlags.None); MongoDBSingleton.Instance.Remove(Query.EQ("timeStamp", int.Parse(a.timeStamp)), "TimeCuoInfoCom", RemoveFlags.None); MongoDBSingleton.Instance.Remove(Query.EQ("timeStamp", int.Parse(a.timeStamp)), "TimeCuoInfoComTwo", RemoveFlags.None); } }); } } /// /// ERP交互方法:打包下线任务创建前 调用 批号主档 接口 /// /// /// public static bool ERPApiFunc(string timeStamp) { bool result = false; try { var model = MongoDBSingleton.Instance.FindOne(Query.EQ("timeStamp", int.Parse(timeStamp)), "TimeCuoInfoCom"); if (model != null) { string userToken = ERPGetLogin(); if (!string.IsNullOrEmpty(userToken)) { // 打包下线任务创建前 调用 批号主档 接口 result = ERPBatchInfo(userToken, model); } else CMMLog.Error($"ERPApiFunc Error:未获取到userToken."); } else CMMLog.Error($"ERPApiFunc Error:当前任务未获取到对应的时间戳数据。时间戳:{timeStamp},时间戳表:TimeCuoInfoCom"); } catch(Exception ex) { CMMLog.Error($"ERPApiFun Error:{ex.Message}"); } return result; } /// /// ERP交互方法:任务完成调用 条码主档 接口 /// /// /// public static bool ERPApiFuncTwo(string timeStamp) { bool result = false; try { var model = MongoDBSingleton.Instance.FindOne(Query.EQ("timeStamp", int.Parse(timeStamp)), "TimeCuoInfoCom"); if (model != null) { string userToken = ERPGetLogin(); if (!string.IsNullOrEmpty(userToken)) { // 任务完成调用 条码主档 接口 result = ERPBarCodeInfo(userToken, model); } else CMMLog.Error($"ERPApiFuncTwo Error:未获取到userToken."); } else CMMLog.Error($"ERPApiFuncTwo Error:当前任务未获取到对应的时间戳数据。时间戳:{timeStamp},时间戳表:TimeCuoInfoCom"); } catch (Exception ex) { CMMLog.Error($"ERPApiFuncTwo Error:{ex.Message}"); } return result; } public static string CooKie = ""; /// /// ERP登录接口 /// public static string ERPGetLogin() { // 获取配置文件数据 string userToken = ""; try { string res = JsonConvert.SerializeObject(new { parameters = new ArrayList { LoginInfo[0], LoginInfo[1], LoginInfo[2], int.Parse(LoginInfo[3]) } }); string feedback = ""; string url = Settings.GetThirdUrlList().Where(a => a.UrlNo == "1" && a.enable == 1).FirstOrDefault().Url; CMMLog.Info($"ERPGetLogin Res:{res},url:{url}"); feedback = api.WebPost(url, res,"","GetCooKie"); CMMLog.Info($"ERPGetLogin Req:{feedback}"); if (!string.IsNullOrEmpty(feedback)) { var response = JsonConvert.DeserializeObject(feedback); if (response.IsSuccessByAPI && !string.IsNullOrEmpty(CooKie)) userToken = CooKie; else CMMLog.Info($"ERPGetLogin:调用接口失败,获取Cookie失败。"); } } catch (Exception ex) { CMMLog.Error($"WMSPost WmsInTask Error:{ex.Message}"); } CMMLog.Info($"ERPGetLogin userToken:{userToken}"); return userToken; } public class ERPGetLoginResModel { public string Message { get; set; } public string MessageCode { get; set; } public int LoginResultType { get; set; } public ERPGetLoginResContextModel Context { get; set; } public class ERPGetLoginResContextModel { public string UserToken { get; set; } } /// /// 接口调用状态 成功-true 失败-false /// public bool IsSuccessByAPI { get; set; } } /// /// 发送ERP批号主档数据 /// /// public static bool ERPBatchInfo(string userToken, TimeCuoInfoCom model) { bool result = false; try { ERPBatchInfoModel sendInfo = new ERPBatchInfoModel(); sendInfo.Model.FCreateOrgId.FNumber = model.createOrganization; sendInfo.Model.FMaterialID.FNumber = model.materialCode; sendInfo.Model.FNumber = model.batchNumber; sendInfo.Model.FProduceDeptID.FNumber = model.workshopCode; sendInfo.Model.FInStockDate = model.BusinessDate; string res = JsonConvert.SerializeObject(new { parameters = new ArrayList { "BD_BatchMainFile", JsonConvert.SerializeObject(sendInfo) } }); string feedback = ""; string url = Settings.GetThirdUrlList().Where(a => a.UrlNo == "3" && a.enable == 1).FirstOrDefault().Url; CMMLog.Info($"ERPBatchInfo Res:{res},Cookie:{userToken},url:{url}"); feedback = api.WebPost(url, res, userToken); CMMLog.Info($"ERPBatchInfo Req:{feedback}"); if (!string.IsNullOrEmpty(feedback)) { var response = JsonConvert.DeserializeObject(feedback); result = response.Result.ResponseStatus.IsSuccess; } } catch (Exception ex) { CMMLog.Error($"ERPBatchInfo WmsInTask Error:{ex.Message}"); } return result; } public class ERPBatchInfoModel { public string Creator { get; set; } = ""; public Array NeedUpDateFields { get; set; } = new Array[0]; public Array NeedReturnFields { get; set; } = new Array[0]; public string IsDeleteEntry { get; set; } = "true"; public string SubSystemId { get; set; } = ""; public string IsVerifyBaseDataField { get; set; } = "false"; public string IsEntryBatchFill { get; set; } = "true"; public string ValidateFlag { get; set; } = "true"; public string NumberSearch { get; set; } = "true"; public string InterationFlags { get; set; } = ""; public string IsAutoSubmitAndAudit { get; set; } = "false"; public ModelModel Model { get; set; } = new ModelModel(); public class ModelModel { public int FLOTID { get; set; } = 0; public FCreateOrgIdModel FCreateOrgId { get; set; } = new FCreateOrgIdModel(); public class FCreateOrgIdModel { /// /// 创建组织 /// public string FNumber { get; set; } } public FMaterialIDModel FMaterialID { get; set; } = new FMaterialIDModel(); public class FMaterialIDModel { /// /// 物料编码 /// public string FNumber { get; set; } } /// /// 批号 /// public string FNumber { get; set; } public FProduceDeptIDModel FProduceDeptID { get; set; } = new FProduceDeptIDModel(); public class FProduceDeptIDModel { /// /// 车间编码 /// public string FNumber { get; set; } } /// /// 业务日期 /// public string FInStockDate { get; set; } } } /// /// 发送ERP条码主档数据 /// /// public static bool ERPBarCodeInfo(string userToken, TimeCuoInfoCom model) { bool result = false; try { ERPBarCodeInfoModel sendInfo = new ERPBarCodeInfoModel(); sendInfo.Model.FBarCode = model.barcode; sendInfo.Model.FBarCodeRule.FNumber = model.codeRules; sendInfo.Model.FMaterialID.FNumber = model.materialCode; sendInfo.Model.F_JY_CZZ.FStaffNumber = model.employeeId.ToString(); sendInfo.Model.FCreateOrgId.FNumber = model.createOrganization; sendInfo.Model.FLot.FNumber = model.batchNumber; sendInfo.Model.FUnitId.FNumber = model.measurementUnit; sendInfo.Model.FQty = model.count; sendInfo.Model.FStockId.FNumber = model.WarehouseCode; sendInfo.Model.FDeptId.FNumber = model.workshopCode; sendInfo.Model.FBillDate = model.BusinessDate; string res = JsonConvert.SerializeObject(new { parameters = new ArrayList { "BD_BarCodeMainFile", JsonConvert.SerializeObject(sendInfo) } }); string feedback = ""; string url = Settings.GetThirdUrlList().Where(a => a.UrlNo == "2" && a.enable == 1).FirstOrDefault().Url; CMMLog.Info($"ERPBarCodeInfo Res:{res},Cookie:{userToken},url:{url}"); feedback = api.WebPost(url, res, userToken); CMMLog.Info($"ERPBarCodeInfo Req:{feedback}"); if (!string.IsNullOrEmpty(feedback)) { var response = JsonConvert.DeserializeObject(feedback); result = response.Result.ResponseStatus.IsSuccess; } } catch (Exception ex) { CMMLog.Error($"ERPBarCodeInfo Error:{ex.Message}"); } return result; } public class ERPBarCodeInfoModel { public string Creator { get; set; } = ""; public Array NeedUpDateFields { get; set; } = new Array[0]; public Array NeedReturnFields { get; set; } = new Array[0]; public string IsDeleteEntry { get; set; } = "true"; public string SubSystemId { get; set; } = ""; public string IsVerifyBaseDataField { get; set; } = "false"; public string IsEntryBatchFill { get; set; } = "true"; public string ValidateFlag { get; set; } = "true"; public string NumberSearch { get; set; } = "true"; public string InterationFlags { get; set; } = ""; public string IsAutoSubmitAndAudit { get; set; } = "false"; public ModelModel Model { get; set; } = new ModelModel(); public class ModelModel { public int FID { get; set; } = 0; /// /// 条形码 /// public string FBarCode { get; set; } public FBarCodeRuleModel FBarCodeRule { get; set; } = new FBarCodeRuleModel(); public class FBarCodeRuleModel { /// /// 条码规则 /// public string FNumber { get; set; } } public FMaterialIDModel FMaterialID { get; set; } = new FMaterialIDModel(); public class FMaterialIDModel { /// /// 物料编码 /// public string FNumber { get; set; } } public F_JY_CZZModel F_JY_CZZ { get; set; } = new F_JY_CZZModel(); public class F_JY_CZZModel { /// /// 员工编号 原先:FNumber 目前:FStaffNumber /// public string FStaffNumber { get; set; } } public FCreateOrgIdModel FCreateOrgId { get; set; } = new FCreateOrgIdModel(); public class FCreateOrgIdModel { /// /// 创建组织 /// public string FNumber { get; set; } } public FLotModel FLot { get; set; } = new FLotModel(); public class FLotModel { /// /// 批号 /// public string FNumber { get; set; } } public FUnitIdModel FUnitId { get; set; } = new FUnitIdModel(); public class FUnitIdModel { /// /// 计量单位 /// public string FNumber { get; set; } } /// /// 数量 /// public int FQty { get; set; } public FStockIdModel FStockId { get; set; } = new FStockIdModel(); public class FStockIdModel { /// /// 仓库编码 /// public string FNumber { get; set; } } public FDeptIdModel FDeptId { get; set; } = new FDeptIdModel(); public class FDeptIdModel { /// /// 车间编码 /// public string FNumber { get; set; } } /// /// 业务日期 /// public string FBillDate { get; set; } } } public class ERPResModel { public ResultModel Result { get; set; } public class ResultModel { public ResponseStatusModel ResponseStatus { get; set; } public class ResponseStatusModel { public bool IsSuccess { get; set; } public int MsgCode { get; set; } } } } /// /// 写入包装机物料信息 /// /// public static void WriteItemInfo(Settings.PlcInfo plcInfo) { CMMLog.Debug($"WriteItemInfo:Start!"); try { //读取【翻页】通道数据 var result = OITcpHelper.RegisterReadOutPut(new OITcpHelper.RegisterReadOutPutModel { dataNum = 1, addr = plcInfo.FyReadAddr, host = plcInfo.ip, port = plcInfo.port }); CMMLog.Debug($"WriteItemInfo:读取【翻页】通道数据为:{JsonConvert.SerializeObject(result)}!"); if (true) // result != null && result.errCode == 0 { // 示例:读出值为1 获取1~5编号的物料数据;读出值为2 获取6~10编号的物料数据 规则 result.result[0] * 5 - 4 起始编号 //int startItemNo = 1; int startItemNo = result.result[0] * 5 - 4; CMMLog.Debug($"WriteItemInfo:翻页数据为:{startItemNo}!"); var reLocationTask = MongoDBSingleton.Instance.Find(Query.And(Query.In("item_no", new List() { startItemNo, startItemNo + 1, startItemNo + 2, startItemNo + 3, startItemNo + 4 })), "ERPItemTable").ToList(); int reLocationTaskNum = reLocationTask != null ? reLocationTask.Count : 0; CMMLog.Debug($"WriteItemInfo:查询出ERP物料表数据数量为:{reLocationTaskNum}!备注:只有数量为5才会写入数据"); if (reLocationTaskNum == 5) { int no = 0; reLocationTask.ForEach(a => { int writeAddr = plcInfo.FyWriteAddr + no * 100; no++; // 解析物料数据并写入 有效数据通道 70,共100(产品批次号-20 产品型号-10 物料编码-20 物料名称-15 计量单位-5 剩余30无用通道) int[] num = new int[100]; // 内存地址 0~19 协议地址 1~20 批次号 人工输入,不需要程序写入 for (int i = 0; i <= 19; i++) num[i] = 0; // 内存地址 20~29 协议地址 21~30 产品型号 // HandleItemInfo(a.item_spec, 20, 29, num); HandleItemInfoChina(a.item_spec, 20, 29, num); CMMLog.Debug($"WriteItemInfo:物料信息处理-2。处理数据:{a.item_spec},处理后数据:{JsonConvert.SerializeObject(num)}"); // 内存地址 30~49 协议地址 31~50 物料编码 HandleItemInfo(a.item_code, 30, 49, num); CMMLog.Debug($"WriteItemInfo:物料信息处理-2。处理数据:{a.item_code},处理后数据:{JsonConvert.SerializeObject(num)}"); // 内存地址 50~64 协议地址 51~65 物料名称 // HandleItemInfo(a.item_name, 50, 64, num); HandleItemInfoChina(a.item_name, 50, 64, num);// 中文处理 CMMLog.Debug($"WriteItemInfo:物料信息处理-2。处理数据:{a.item_name},处理后数据:{JsonConvert.SerializeObject(num)}"); // 内存地址 65~69 协议地址 66~70 计量单位 HandleItemInfo(a.item_uom, 65, 69, num); CMMLog.Debug($"WriteItemInfo:物料信息处理-2。处理数据:{a.item_uom},处理后数据:{JsonConvert.SerializeObject(num)}"); // 内存地址 70~79 协议地址 71~100 空余地址 for (int i = 70; i <= 99; i++) num[i] = 0; CMMLog.Debug($"WriteItemInfo:发送物料信息。序号:{a.item_no},ip:{plcInfo.ip},port:{plcInfo.port},写入起始地址:{writeAddr},写入数据:{JsonConvert.SerializeObject(num)}"); var wirteall01 = OITcpHelper.RegisterWriteOutPutMulti(new OITcpHelper.RegisterWriteOutPutModelMulti { addr = writeAddr, host = plcInfo.ip, port = plcInfo.port, data = num }); int writeResult = wirteall01 != null ? wirteall01.errCode : 1; CMMLog.Debug($"WriteItemInfo:发送物料信息。序号:{a.item_no},写入结果:{writeResult}。ip:{plcInfo.ip},port:{plcInfo.port},写入起始地址:{writeAddr},写入数据:{JsonConvert.SerializeObject(num)}"); }); } } else CMMLog.Debug($"WriteItemInfo:未读取【翻页】通道数据!"); } catch(Exception ex) { CMMLog.Debug($"WriteItemInfo Error:{ex.Message}"); } CMMLog.Debug($"WriteItemInfo:End!"); } /// /// 写入包装机物料信息 /// /// public static void WriteItemInfoTwo(Settings.PlcInfo plcInfo) { CMMLog.Debug($"WriteItemInfoTwo:Start!"); try { //读取【翻页】通道数据 var result = OITcpHelper.RegisterReadOutPut(new OITcpHelper.RegisterReadOutPutModel { dataNum = 1, addr = plcInfo.FyReadAddr, host = plcInfo.ip, port = plcInfo.port }); CMMLog.Debug($"WriteItemInfoTwo:读取【翻页】通道数据为:{JsonConvert.SerializeObject(result)}!"); if (true) // result != null && result.errCode == 0 { // 示例:读出值为1 获取1~5编号的物料数据;读出值为2 获取6~10编号的物料数据 规则 result.result[0] * 5 - 4 起始编号 //int startItemNo = 1; int startItemNo = result.result[0] * 5 - 4; CMMLog.Debug($"WriteItemInfoTwo:翻页数据为:{startItemNo}!"); var reLocationTask = MongoDBSingleton.Instance.Find(Query.And(Query.In("item_no", new List() { startItemNo, startItemNo + 1, startItemNo + 2, startItemNo + 3, startItemNo + 4 })), "ERPItemTable").ToList(); int reLocationTaskNum = reLocationTask != null ? reLocationTask.Count : 0; CMMLog.Debug($"WriteItemInfoTwo:查询出ERP物料表数据数量为:{reLocationTaskNum}!备注:只有数量为5才会写入数据"); if (reLocationTaskNum == 5) { int no = 0; reLocationTask.ForEach(a => { int writeAddr = plcInfo.FyWriteAddr + no * 50; if (no > 0) writeAddr = writeAddr + 40; no++; // 解析物料数据并写入 有效数据通道 50,50(产品型号-10 物料编码-15 物料名称-20 计量单位-5) int[] num = new int[50]; // 内存地址 0~19 协议地址 1~20 批次号 人工输入,不需要程序写入 for (int i = 0; i <= 19; i++) num[i] = 0; // 内存地址 20~29 协议地址 21~30 产品型号 // HandleItemInfo(a.item_spec, 20, 29, num); HandleItemInfoChina(a.item_spec, 0, 9, num); CMMLog.Debug($"WriteItemInfoTwo:物料信息处理-2。处理数据:{a.item_spec},处理后数据:{JsonConvert.SerializeObject(num)}"); // 内存地址 30~49 协议地址 31~50 物料编码 HandleItemInfo(a.item_code, 10, 24, num); CMMLog.Debug($"WriteItemInfoTwo:物料信息处理-2。处理数据:{a.item_code},处理后数据:{JsonConvert.SerializeObject(num)}"); // 内存地址 50~64 协议地址 51~65 物料名称 // HandleItemInfo(a.item_name, 50, 64, num); HandleItemInfoChina(a.item_name, 25, 44, num);// 中文处理 CMMLog.Debug($"WriteItemInfoTwo:物料信息处理-2。处理数据:{a.item_name},处理后数据:{JsonConvert.SerializeObject(num)}"); // 内存地址 65~69 协议地址 66~70 计量单位 HandleItemInfo(a.item_uom, 45, 49, num); CMMLog.Debug($"WriteItemInfoTwo:物料信息处理-2。处理数据:{a.item_uom},处理后数据:{JsonConvert.SerializeObject(num)}"); CMMLog.Debug($"WriteItemInfoTwo:发送物料信息。序号:{a.item_no},ip:{plcInfo.ip},port:{plcInfo.port},写入起始地址:{writeAddr},写入数据:{JsonConvert.SerializeObject(num)}"); var wirteall01 = OITcpHelper.RegisterWriteOutPutMulti(new OITcpHelper.RegisterWriteOutPutModelMulti { addr = writeAddr, host = plcInfo.ip, port = plcInfo.port, data = num }); int writeResult = wirteall01 != null ? wirteall01.errCode : 1; CMMLog.Debug($"WriteItemInfoTwo:发送物料信息。序号:{a.item_no},写入结果:{writeResult}。ip:{plcInfo.ip},port:{plcInfo.port},写入起始地址:{writeAddr},写入数据:{JsonConvert.SerializeObject(num)}"); }); } } else CMMLog.Debug($"WriteItemInfoTwo:未读取【翻页】通道数据!"); } catch (Exception ex) { CMMLog.Debug($"WriteItemInfoTwo Error:{ex.Message}"); } CMMLog.Debug($"WriteItemInfoTwo:End!"); } public static void HandleItemInfo(string itemInfo,int startIndex, int endIndex , int[] num) { string data = itemInfo;// 要写入的处理后数据 string dataHeader = "";// 数据头处理 int dataCutCont = 0;// 数据截取开关 if (itemInfo.Length % 2 != 0) { data = "0" + itemInfo; dataHeader = "" + itemInfo.Substring(0, 1); } int maxLength = startIndex - 1 + (data.Length / 2);// data.Length / 2 至少为 1 for (int i = startIndex; i <= maxLength; i++) { num[i] = int.Parse(PLCControl.AsciiToTen(data.Substring(dataCutCont, 2))); dataCutCont = dataCutCont + 2; } if (!string.IsNullOrEmpty(dataHeader)) num[startIndex] = int.Parse(PLCControl.AsciiToTen(dataHeader)); for (int i = maxLength + 1; i <= endIndex; i++) num[i] = 0;//将当前处理完数据的其他无数据的通道全部置为 0 CMMLog.Debug($"WriteItemInfo:物料信息处理-1。处理数据:{itemInfo},处理后数据:{JsonConvert.SerializeObject(num)}"); } public static void HandleItemInfoChina(string itemInfo, int startIndex, int endIndex, int[] num) { string data = itemInfo;// 要写入的处理后数据 int dataCutCont = 0;// 数据截取开关 int maxLength = startIndex - 1 + data.Length;// data.Length / 2 至少为 1 for (int i = startIndex; i <= maxLength; i++) { num[i] = Test.ConvertToAscii(char.Parse(data.Substring(dataCutCont, 1))); dataCutCont = dataCutCont + 1; } for (int i = maxLength + 1; i <= endIndex; i++) num[i] = 0;//将当前处理完数据的其他无数据的通道全部置为 0 CMMLog.Debug($"WriteItemInfo:物料信息处理-1。处理数据:{itemInfo},处理后数据:{JsonConvert.SerializeObject(num)}"); } /// /// 获取员工编码 /// /// public static string GetEmployeeId(int readAddr,string ip,int port) { string employeeId = ""; var employeeIdAction = OITcpHelper.RegisterReadOutPut(new OITcpHelper.RegisterReadOutPutModel { addr = readAddr, host = ip, port = port, dataNum = 2 }); employeeId = Convert.ToInt32(PLCControl.Completion(employeeIdAction.result[0]) + PLCControl.Completion(employeeIdAction.result[1]), 2).ToString(); return employeeId; } public static string packageCont = "1";// 包装机复称UI变更功能开关 1-开启 0-关闭 /// /// 插入包装机信息表 /// public static void packageInfo(string machineNo, string trayCode, string lotNo, string oneTrayWeight) { if (packageCont == "1") { try { MongoDBSingleton.Instance.Insert(new packageInfoModel { machineNo = machineNo, trayCode = trayCode, batchNo = lotNo, time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), weight = oneTrayWeight, CreateTime = DateTime.Now.AddHours(8) }, "packageInfoModel"); } catch (Exception ex) { CMMLog.Error($"packageInfo Error:{ex.Message}"); } } } public static void updatePackageInfo(string machince, string trayCode, int[] result) { if (packageCont == "1") { try { var queryList = MongoDBSingleton.Instance.Find(Query.And(Query.EQ("machineNo", machince), Query.EQ("trayCode", trayCode), Query.EQ("weight2", "")), "packageInfoModel"); if (queryList.Count > 0) { packageInfoModel query = queryList.OrderByDescending(a => a.time).First(); if (query != null) { CMMLog.Debug($"updatePackageInfo:{query.machineNo},trayCode:{query.trayCode},weight:{query.weight}"); //读取复称平台的重量 result[17]) + PLCControl.Completion(result[18] double x = (double)Convert.ToInt32(PLCControl.Completion(result[19]) + PLCControl.Completion(result[20]), 2) / 100; string weight = x.ToString(); CMMLog.Debug($"updatePackageInfo:原始复称重量数据:{result[19]},{result[20]};转换后复称重量数据:{weight}"); //重量差值 //string weightDifference = (double.Parse(query.weight) - x).ToString(); string weightDifference = Math.Round((double.Parse(query.weight) - x), 2).ToString(); //CMMLog.Info($"weightDifference2:{weightDifference2}"); //将复称平台重量写入中间表 MongoDBSingleton.Instance.Update(Query.And(Query.EQ("machineNo", machince), Query.EQ("time", query.time), Query.EQ("trayCode", query.trayCode), Query.EQ("weight2", "")), Update.Set("weight2", weight).Set("weightDifference", weightDifference), UpdateFlags.None); } else CMMLog.Debug($"数据查询失败"); } else CMMLog.Debug($"updatePackageInfo:packageInfoModel未找到数据,machineNo:{machince},trayCode:{trayCode}"); } catch (Exception ex) { CMMLog.Error($"updatePackageInfo Error:{ex.Message}"); } } } public static void deletePackageInfo() { if (packageCont == "1") { try { var request = MongoDBSingleton.Instance.FindAll(); if (request.Count > 0) { request.ForEach(a => { if (DateTime.Now.Subtract(a.CreateTime).TotalDays > 7) { MongoDBSingleton.Instance.Remove(Query.EQ("_id", a._id), "packageInfoModel", RemoveFlags.None); } }); } } catch (Exception ex) { CMMLog.Error($"deletePackageInfo Error:{ex.Message}"); } } } internal static void insertMidTable() { var db = new SqlHelper().GetInstance(false); bool resul = false; //CMMLog.Info($"查询【T_JY_MATERIALSync】表,查询条件:a.FWorkShopNumber == BM000161 && a.FUseOrgNumber == 02"); var materInfo = db.Queryable().Where(a => a.FWorkShopNumber == "BM000161" && a.FUseOrgNumber == "02").ToList(); if (materInfo.Count > 0) { //CMMLog.Info($"查询【T_JY_MATERIALSync】的数量为:{materInfo.Count}"); var itemList = MongoDBSingleton.Instance.FindAll(); if (itemList.Count != materInfo.Count) { MongoDBSingleton.Instance.RemoveAll("ERPItemTable"); } foreach (var a in materInfo) { var itemInfo = MongoDBSingleton.Instance.FindOne(Query.EQ("item_code", a.FNumber), "ERPItemTable"); if (itemInfo == null) { CMMLog.Info($"中间表【ERPItemTable】未查询到数据,物料编码:{a.FNumber}"); int itemNo = 1; // 获取最大序号的数据 var maxErpItemInfoList = MongoDBSingleton.Instance.FindAll("ERPItemTable"); if (maxErpItemInfoList.Count > 0) { var maxErpItemInfo = maxErpItemInfoList.OrderByDescending(it => it.item_no).First(); if (maxErpItemInfo != null) itemNo = maxErpItemInfo.item_no + 1; } CMMLog.Info($"获取插入序号:{itemNo}"); MongoDBSingleton.Instance.Insert(new ERPItemTable { item_no = itemNo, item_code = a.FNumber, item_name = a.FName, item_spec = a.FSpecification, item_uom = a.FStoreUnit, dateTime = DateTime.Now }, "ERPItemTable"); resul = true; } else { //查询数据是否相同 if (itemInfo.item_name != a.FName || itemInfo.item_spec != a.FSpecification || itemInfo.item_uom != a.FStoreUnit) { var query = Query.EQ("item_code", a.FName); var update = Update.Set("item_name", a.FName).Set("item_spec", a.FSpecification) .Set("item_uom", a.FStoreUnit).Set("dateTime", DateTime.Now); MongoDBSingleton.Instance.Update(query, update, "ERPItemTable", MongoDB.Driver.UpdateFlags.None); resul = true; } } } } var empInfo = db.Queryable().ToList(); if (empInfo.Count > 0) { var empList = MongoDBSingleton.Instance.FindAll(); if (empList.Count != empInfo.Count) { MongoDBSingleton.Instance.RemoveAll("ERPEmployeeTable"); } foreach (var a in empInfo) { var erpEmpInfo = MongoDBSingleton.Instance.FindOne(Query.EQ("item_code", a.FNumber), "ERPEmployeeTable"); if (erpEmpInfo == null) { CMMLog.Info($"中间表【ERPEmployeeTable】未查询到数据,物料编码:{a.FNumber}"); int itemNo = 1; // 获取最大序号的数据 var maxErpEmpInfoList = MongoDBSingleton.Instance.FindAll("ERPEmployeeTable"); if (maxErpEmpInfoList.Count > 0) { var maxErpEmpInfo = maxErpEmpInfoList.OrderByDescending(it => it.item_no).First(); if (maxErpEmpInfo != null) itemNo = maxErpEmpInfo.item_no + 1; } CMMLog.Info($"获取插入序号:{itemNo}"); MongoDBSingleton.Instance.Insert(new ERPEmployeeTable { item_no = itemNo, item_code = a.FNumber, item_name = a.FName, employee_id = a.FStaffNumber, dateTime = DateTime.Now }, "ERPEmployeeTable"); resul = true; } else { if (erpEmpInfo.employee_id != a.FStaffNumber) { var query = Query.EQ("item_code", a.FNumber); var update = Update.Set("item_name", a.FName).Set("employee_id", a.FStaffNumber) .Set("dateTime", DateTime.Now); MongoDBSingleton.Instance.Update(query, update, "ERPEmployeeTable", MongoDB.Driver.UpdateFlags.None); resul = true; } } } } if (resul) { if (!ERPService.WriteEmpAndItemInfoTwo()) { //清空表数据 MongoDBSingleton.Instance.RemoveAll("ERPItemTable"); MongoDBSingleton.Instance.RemoveAll("ERPEmployeeTable"); } } } internal static bool WriteEmpAndItemInfoTwo() { try { TcpClient client = new TcpClient("10.50.65.30", 3001); CMMLog.Info("WriteEmpAndItemInfoTwo 已连接到服务器"); NetworkStream stream = client.GetStream(); List paddedData = new List(); var encode = Encoding.GetEncoding("GB2312"); int i = 0; while (i < 150) { if (i < 100) { //员工编号 var erpInfo = MongoDBSingleton.Instance.FindOne(Query.EQ("item_no", i + 1), "ERPEmployeeTable"); if (erpInfo != null && !string.IsNullOrEmpty(erpInfo.employee_id)) { // 内存地址 0~4 协议地址 1~5 计量单位 byte[] data1 = encode.GetBytes(erpInfo.employee_id); byte[] paddedData1 = new byte[10]; Array.Copy(data1, 0, paddedData1, 0, Math.Min(data1.Length, 10)); // 将数组转换为列表 paddedData.AddRange(paddedData1); } else { paddedData.AddRange(new byte[10]); } } else { int itemNo = i - 99; //物料信息 var itemInfo = MongoDBSingleton.Instance.FindOne(Query.EQ("item_no", itemNo), "ERPItemTable"); if (itemInfo != null) { // 将数组转换为列表 paddedData.AddRange(getBuff(itemInfo.item_spec, 20, 2)); paddedData.AddRange(getBuff(itemInfo.item_code, 40, 1)); paddedData.AddRange(getBuff(itemInfo.item_name, 30, 3)); paddedData.AddRange(getBuff(itemInfo.item_uom, 10, 1)); } else { paddedData.AddRange(new byte[100]); } } i++; } byte[] combinedArray = paddedData.ToArray(); stream.Write(combinedArray, 0, combinedArray.Length); CMMLog.Info("WriteEmpAndItemInfoTwo:" + JsonConvert.SerializeObject(combinedArray)); //CMMLog.Info($"WriteEmpAndItemInfoTwo {combinedArray.Length}"); //CMMLog.Info($"Received: {encode.GetString(combinedArray, 0, 6000)}"); return true; } catch (Exception ex) { CMMLog.Info("WriteEmpAndItemInfoTwo err:" + ex.Message); return false; //WriteEmpAndItemInfoTwo(); } } private static byte[] getBuff(string value, int bit, int result) { byte[] data1 = Encoding.GetEncoding("GB2312").GetBytes(value); if (result == 2) data1 = Encoding.UTF8.GetBytes(value); if (result == 3) data1 = Encoding.BigEndianUnicode.GetBytes(value); byte[] paddedData1 = new byte[bit]; Array.Copy(data1, 0, paddedData1, 0, Math.Min(data1.Length, bit)); // 将数据复制到6000字节的缓冲区中 return paddedData1; } public class packageInfoModel { public ObjectId _id { get; set; } /// /// 包装机号 /// public string machineNo { get; set; } = ""; /// /// 托盘号 /// public string trayCode { get; set; } = ""; /// /// 批次号 /// public string batchNo { get; set; } = ""; /// /// 下料时间 /// public string time { get; set; } = ""; /// /// 重量 /// public string weight { get; set; } = ""; /// /// 复称重量 /// public string weight2 { get; set; } = ""; /// /// 重量差值 /// public string weightDifference { get; set; } = ""; /// /// 创建时间 /// public DateTime CreateTime { get; set; } } } }