using Hanhe.iWCS.Business; 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 SqlSugar; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using static Hanhe.iWCS.IndonesiaGLMProtocol.ApiHelper; using static Hanhe.iWCS.IndonesiaGLMProtocol.MESHelper; namespace Hanhe.iWCS.IndonesiaGLMProtocol { 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 DateTime dateTime { get; set; } } public static void SendERPTaskInfo(TN_I_TASK_MST mst) { CMMLog.Info($"SendERPTaskInfo 插入数据 开始,任务号:{mst.CN_S_TASK_NO}"); var sendERPTaskInfo = MongoDBSingleton.Instance.Find(Query.EQ("isFinish", "N")); if (sendERPTaskInfo.Count > 0) { SendErpTaskInfoTable x = sendERPTaskInfo.OrderBy(a => a.dateTime).FirstOrDefault(); CMMLog.Info($"SendERPTaskInfo 插入数据:{JsonConvert.SerializeObject(x)}"); MongoDBSingleton.Instance.Update(Query.EQ("_id", x._id), Update.Set("isFinish", "Y"), "SendErpTaskInfoTable", UpdateFlags.None); } else CMMLog.Error($"SendERPTaskInfo Error:当前中间表无下线任务"); } public class SendErpTaskInfoTable { public ObjectId _id { get; set; } /// /// 条形码 /// public string barcode { get; set; } /// /// 条码规则 /// public string codeRules { get; set; } /// /// 物料编码(唯一) /// public string materialCode { get; set; } /// /// 创建组织 /// public string createOrganization { get; set; } /// /// 产品批次号 /// public string batchNumber { get; set; } /// /// 计量单位 /// public string measurementUnit { get; set; } /// /// 数量 /// public int count { get; set; } /// /// 仓库编码 /// public string WarehouseCode { get; set; } /// /// 车间编码 /// public string workshopCode { get; set; } /// /// 业务日期 /// public DateTime BusinessDate { get; set; } /// /// 生产日期 /// public DateTime FProductionDate { get; set; } /// /// 有效期 /// public DateTime FExpirationDate { get; set; } /// /// 员工编号1 /// public string employeeID1 { get; set; } /// /// 产品需求重量1:32位整数 /// public int needWeight_1 { get; set; } /// /// 单托实际重量1:32位整数 /// public int realWeight_1 { get; set; } /// /// 叠托后的实际重量:32位整数 /// public int totalWeight { get; set; } /// /// 是否入库完成 /// public string isFinish { get; set; } = "N"; public DateTime dateTime { get; set; } } /// /// 入库任务完成回报ERP信息 /// /// /// public static void SendERPTaskCompleteFunc() { try { var db = new SqlHelper().GetInstance(); var a = MongoDBSingleton.Instance.FindOne("SendErpTaskInfoTable"); if (a != null) { // 先根据任务批次号字段获取时间戳中间表-TimeCuoInfoCom 数据,并进行后续调用,处理成功删除时间戳中间表-TimeCuoInfoCom 数据 #region 计算单据编号 //string FBillNO = ""; //int num = 0; //string S_NUM = ""; //string time = DateTime.Now.ToString("yyMMdd"); //CMMLog.Info($"SendERPTaskCompleteFunc time:{time}"); //var midInfo = db.Queryable().Where(b => b.time == time).First(); //if (midInfo != null) //{ // midInfo.num = midInfo.num + 1; // num = midInfo.num; // db.Updateable(midInfo).UpdateColumns(b => new { b.num }).ExecuteCommand(); //} //else //{ // num = 1; // midInfo = new ADDMid // { // time = DateTime.Now.ToString("yyMMdd"), // num = 1 // }; // db.Insertable(midInfo).ExecuteCommand(); //} // //CMMLog.Info($"SendERPTaskCompleteFunc num: {num}"); //for (int i = num.ToString().Length + 1; i <= 4; i++) //{ // S_NUM = S_NUM + "0"; //} // //FBillNO = "ARKD" + DateTime.Now.ToString("yyMMdd") + S_NUM + num.ToString(); //CMMLog.Info($"SendERPTaskCompleteFunc: {FBillNO}"); #endregion //int n = 0; //行号 //n = n + 1; CMMLog.Info($"SendERPTaskCompleteFunc:INSERT INTO T_JY_BARCODESync (FBarCode,FBarCodeRule,FMaterialNumber,FCreateOrgNumber,FLot,FUnit,FQty,FStockNumber,FDept,FBillDate,FProductionDate,FExpirationDate,F_JY_CZZ,FCreateTime,FOpStatus) VALUES ('{a.barcode}','{a.codeRules}','{a.materialCode}','02','{a.batchNumber}','{a.measurementUnit}','{a.count}','{a.WarehouseCode}','{a.workshopCode}','{a.BusinessDate}','{a.FProductionDate}','{a.FExpirationDate}','{a.employeeID1}','{a.dateTime}','0')"); string sql = $"INSERT INTO T_JY_BARCODESync (FBarCode,FBarCodeRule,FMaterialNumber,FCreateOrgNumber,FLot,FUnit,FQty,FStockNumber,FDept,FBillDate,FProductionDate,FExpirationDate,F_JY_CZZ,FCreateTime,FOpStatus) VALUES ('{a.barcode}','{a.codeRules}','{a.materialCode}','02','{a.batchNumber}','{a.measurementUnit}','{a.count}','{a.WarehouseCode}','{a.workshopCode}','{a.BusinessDate}','{a.FProductionDate}','{a.FExpirationDate}','{a.employeeID1}','{a.dateTime}','0')"; if(new SqlHelper().ExecuteSql(sql, false)) { //插入成功 清除中间表 MongoDBSingleton.Instance.Remove(Query.EQ("_id", a._id), "SendErpTaskInfoTable", RemoveFlags.None); //MongoDBSingleton.Instance.Remove(Query.EQ("timeStamp", int.Parse(a.timeStamp)), "TimeCuoInfoCom", RemoveFlags.None); } else { CMMLog.Info("插入失败 ------"); } } } catch (Exception ex) { CMMLog.Info("SendERPTaskCompleteFunc err:" + ex.Message); } } public class ADDMid { [SugarColumn(IsPrimaryKey = true)] public string time { get; set; } public int num { get; set; } } /// /// 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.FNumber = 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 { /// /// 员工编号 /// public string FNumber { 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 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() { try { var db = new SqlHelper().GetInstance(false); bool resul = false; //CMMLog.Info($"查询【T_JY_MATERIALSync】表,查询条件:a.FWorkShopNumber == BM000594 && a.FUseOrgNumber == 02"); var materInfo = db.Queryable().Where(a => a.FWorkShopNumber == "BM000594" && (a.FUseOrgNumber == "146" || a.FUseOrgNumber == "161" || a.FUseOrgNumber == "162" || a.FUseOrgNumber == "165" || a.FUseOrgNumber == "177")).ToList(); if (materInfo.Count > 0) { 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().Take(100).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"); } } } catch(Exception ex) { CMMLog.Info("insertMidTable err"+ex.Message); } } internal static bool WriteEmpAndItemInfoTwo() { try { var plcList = Settings.GetPlcInfo().Where(a => a.deviceType == "1" && a.enable == 1).ToList(); if(plcList.Count > 0) { foreach(var a in plcList) { string ip = a.ip; int port = a.plcPort; TcpClient client = new TcpClient(ip, port); CMMLog.Info($"WriteEmpAndItemInfoTwo 已连接到服务器,ip:{ip},port:{port}"); 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, 3)); paddedData.AddRange(getBuff(itemInfo.item_code, 30, 1)); paddedData.AddRange(getBuff(itemInfo.item_name, 40, 3)); paddedData.AddRange(getBuff(itemInfo.item_uom, 10, 1)); } else { paddedData.AddRange(new byte[100]); } } i++; } byte[] combinedArray = paddedData.ToArray(); if (stream.CanWrite) { stream.Write(combinedArray, 0, combinedArray.Length); CMMLog.Info("WriteEmpAndItemInfoTwo:" + JsonConvert.SerializeObject(combinedArray)); } else { CMMLog.Info("WriteEmpAndItemInfoTwo:不支持写入数据"); } Thread.Sleep(1000); } } //CMMLog.Info($"WriteEmpAndItemInfoTwo {combinedArray.Length}"); //CMMLog.Info($"Received: {encode.GetString(combinedArray, 0, 6000)}"); return true; } catch (IOException ex) { // 处理写入失败的情况 Console.WriteLine("WriteEmpAndItemInfoTwo err 写入失败: " + ex.Message); return false; } 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; } internal static void senderpTask(TimeCuoInfoCom time, string startBit) { try { //CMMLog.Info("插入SendErpTaskInfoTable 表 开始:" + JsonConvert.SerializeObject(time)); var erpInfo = MongoDBSingleton.Instance.FindOne(Query.EQ("timeStamp", time.timeStamp.ToString()), "SendErpTaskInfoTable"); if (erpInfo == null) { CMMLog.Info("插入SendErpTaskInfoTable 表 1"); if(time.BusinessDate.Length == 8) { time.BusinessDate = time.BusinessDate.Substring(0, 4) + "-" + time.BusinessDate.Substring(4, 2) + "-" + time.BusinessDate.Substring(6); } MongoDBSingleton.Instance.Insert(new SendErpTaskInfoTable { barcode = time.barcode, codeRules = time.codeRules, materialCode = time.materialCode, createOrganization = time.createOrganization, batchNumber = time.batchNumber, measurementUnit = time.measurementUnit, count = time.count, WarehouseCode = time.WarehouseCode, workshopCode = time.workshopCode, BusinessDate = Convert.ToDateTime(time.BusinessDate).AddHours(8), FProductionDate = Convert.ToDateTime(time.BusinessDate).AddHours(8), FExpirationDate = Convert.ToDateTime(time.BusinessDate).AddHours(8).AddDays(365), employeeID1 = time.employeeId, dateTime = DateTime.Now.AddHours(8), //变更注释 }, "SendErpTaskInfoTable"); } CMMLog.Info("插入SendErpTaskInfoTable 表 结束"); } catch (Exception ex) { CMMLog.Info("插入SendErpTaskInfoTable 表 err:" + ex.Message); } } 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; } } } }