using System; using System.Collections.Generic; using System.Reflection; using System.Windows.Forms; using Newtonsoft.Json; using System.Net; using System.Threading.Tasks; using System.Threading; using System.Text; using System.Configuration; using System.IO; using EasyModbusClient.redis; using EasyModbusClient.util; using EasyModbusClient.businessBody; using Newtonsoft.Json.Serialization; using EasyModbus; using YG.Device; using YG; using IMCS.Device; using IMCS.Device.body; using Newtonsoft.Json.Linq; using IMCS.Http.businessBody; using IMCS.Lib; using System.Linq; namespace EasyModbusClient { /* * string cmdreceive= CMDLib.Instance.WriteCmd($"netsh http add urlacl url={HttpServerUrlString} user=Everyone"); YG.Log.Instance.WriteLogAdd($"启动HttpServer 默认添加允许项:{cmdreceive}"); System.Threading.Thread.Sleep(500); */ class ControllerHelper { private static string RETVAL = "success"; private static int ASK_TIMES = 20; private static string VirtualProgram = ConfigurationManager.AppSettings["VirtualProgram"]; private static int HEX_BINARY = 8; private uint currentToolArea = 1; private static string ConncetionRedisString = ConfigurationManager.AppSettings["ConncetionRedisString"]; private static string HttpServerUrlString = ConfigurationManager.AppSettings["HttpServerUrlString"]; private static string NcExtendPath = ConfigurationManager.AppSettings["NcExtendPath"]; private static string NcUpLoadPath = ConfigurationManager.AppSettings["NcUpLoadPath"]; private static string LocalNcPath = ConfigurationManager.AppSettings["LocalNcPath"]; private static string ClsSFTP_IP = ConfigurationManager.AppSettings["ClsSFTP_Ip"]; private static string ClsSFTP_Port = ConfigurationManager.AppSettings["ClsSFTP_Port"]; private static string ClsSFTP_UserName = ConfigurationManager.AppSettings["ClsSFTP_UserName"]; private static string ClsSFTP_PWD = ConfigurationManager.AppSettings["ClsSFTP_Pwd"]; private void send(HttpListenerResponse response, short value, string machine = "WL") { ResponseBody responseBody = new ResponseBody(); responseBody.Code = 0; responseBody.Msg = Constants.OPERATE_SUCCESS_MSG; response.StatusCode = 200; response.ContentType = "application/json;charset=UTF-8"; response.ContentEncoding = Encoding.UTF8; response.AppendHeader("Content-Type", "application/json;charset=UTF-8"); using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8)) { string respstring = ""; if (value == -3) { respstring = "关状态"; } else if (value == -4) { respstring = "开状态"; } if (machine == "JC") { switch (value) { case 1: respstring = "执行程序成功"; break; case 2: respstring = "执行程序失败"; break; case 3: respstring = "不满足前置条件"; break; } } if (machine == "WL") { switch (value) { case 1: respstring = "执行取动作"; break; case 4: respstring = "执行放动作"; break; case 7: respstring = "执行移动动作"; break; case 2: respstring = "取执行中"; break; case 3: respstring = "取完成"; break; case 5: respstring = "放执行中"; break; case 6: respstring = "放完成"; break; case 8: respstring = "移动完成"; break; case 9: respstring = "机器人故障"; break; case 10: respstring = "打标完成"; break; case 11: respstring = "清洗剂执行中"; break; case 12: respstring = "不满足清晰条件"; break; } } else if (machine == "LHT") { switch (value) { case 1: respstring = "执行取动作"; break; case 2: respstring = "取完成"; break; case 3: respstring = "执行放动作"; break; case 4: respstring = "放完成"; break; case 5: respstring = "取执行中"; break; case 6: respstring = "放执行中"; break; } } writer.Write(respstring); writer.Close(); response.Close(); } } //httpser服务 public void StartHttpServer() { CommonUtil.InitXml(); HttpListener listener = new HttpListener();// HTTP 协议侦听器 LibCMD.Instance.WriteCmd(HttpServerUrlString); listener.Prefixes.Add(HttpServerUrlString);// 配置访问权限地址 listener.Start(); CommonUtil.WriteAccessLog(DateTime.Now + ">>>监听服务启动Listening>>>>"); Task task = Task.Factory.StartNew(() => { // 创建异步task while (listener.IsListening) { HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; try { Servlet servlet = new MyServlet(); servlet.onCreate(); if (!request.Url.ToString().Contains("favicon")) { if (request.HttpMethod == "POST") { Stream stream = context.Request.InputStream; StreamReader reader = new StreamReader(stream, Encoding.UTF8); string body = reader.ReadToEnd(); YG.Log.Instance.WriteLogAdd(">>>===收到POST数据 : >>>>===" + body); CcsRequestBody ccsRequestBody = JsonJavaScriptSerializer.FromJSON(body); string url = (ccsRequestBody.Url + ":" + ccsRequestBody.Port); string businessType = ccsRequestBody.BusinessType; DeviceList conDeviceInfo = DeviceManage.Instance.GetOne(url); ResponseBody responseBody = ResponseBody.newObject(); response.StatusCode = 200; response.ContentType = "application/json;charset=UTF-8"; response.ContentEncoding = Encoding.UTF8; response.AppendHeader("Content-Type", "application/json;charset=UTF-8"); if (conDeviceInfo != null) { if (!string.IsNullOrEmpty(businessType)) { if (businessType.Equals("testwork")) { conDeviceInfo.DeviceSend("DB200.52", "1111".ReturnBtyesWtitString(40)); System.Threading.Thread.Sleep(1100); conDeviceInfo.DeviceSend("DB200.92", "1111".ReturnBtyesWtitString(20)); } if (businessType.Equals("uploadProgram")) { responseBody = UpLoadNc(conDeviceInfo, ccsRequestBody.Data, ccsRequestBody); } else if (businessType.Equals("deleteProgram")) { responseBody = DeleteNCProgram(conDeviceInfo, ccsRequestBody.Data, ccsRequestBody); } else if (businessType.Equals("execProgram")) { CcsRequestBody itemrequestbody = ccsRequestBody.clone() as CcsRequestBody; DeviceOPCUat itemreadopcua = (DeviceOPCUat)conDeviceInfo; int runcount = 0; Task.Factory.StartNew(async () => { while (true) { runcount++; if (runcount > 10) { break; } await Task.Delay(2000); List itemopcuavalue = itemreadopcua.OpcUa_Read(new List { "/Plc/M1300.0", "/Plc/I37.1" }); if (itemopcuavalue.Where(m => m.Equals("False")).Count() == 0 && itemopcuavalue.Count > 0) // List itemopcuavalue = itemreadopcua.OpcUa_Read(new List { "/Plc/M1300.0"}); //if (itemopcuavalue.Where(m => m.Equals("False")).Count() == 0 && itemopcuavalue.Count > 0) { try { if (SelectedNCProgram(conDeviceInfo, itemrequestbody.Data, itemrequestbody)) { try { System.Threading.Thread.Sleep(2000); responseBody = WriteValue(conDeviceInfo, itemrequestbody, true); break; } catch (Exception eex) { YG.Log.Instance.WriteLogAdd($"247-->程序执行中出现了异常情况-->{eex.Message}"); } } else { YG.Log.Instance.WriteLogAdd($"------------->>>选择程序出现异常"); } } catch (Exception ex) { YG.Log.Instance.WriteLogAdd($"247-->程序出现异常-->{ex.Message}"); } } } }); //将选中程序和执行程序合并 一个指令执行 } else { responseBody = WriteValue(conDeviceInfo, ccsRequestBody, true); } //如果此操作成功,加入回调任务队列 if (responseBody.Code == Constants.RET_SUCCESS_CODE) { callResponse(ccsRequestBody, conDeviceInfo.ServerUrl, Constants.RET_SUCCESS_CODE, Constants.OPERATE_SUCCESS_MSG); } var serializerSettings = new JsonSerializerSettings() { // 设置为驼峰命名 ContractResolver = new CamelCasePropertyNamesContractResolver() }; using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8)) { YG.Log.Instance.WriteLogAdd($"WMS--->>{responseBody.Json_SerializeObject()}--->>{body}\r\n"); writer.Write(JsonConvert.SerializeObject(responseBody, Formatting.Indented, serializerSettings)); writer.Close(); response.Close(); } } } else { using (StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8)) { YG.Log.Instance.WriteLogAdd($"WMS--->>{responseBody.Json_SerializeObject()}--->>{body}\r\n"); responseBody.Code = 3; responseBody.Msg = "无法找到相关设备,请检查网络是否通畅"; writer.Write(responseBody.Json_SerializeObject()); writer.Close(); response.Close(); } YG.Log.Instance.WriteLogAdd("---->>没有检测到当前设备"); } } } } catch (Exception ex) { CommonUtil.WriteAccessLog(DateTime.Now + ">>>===HTTP Server监听器异常 {0}信息 : >>>>===" + ex.ToString()); listener.Stop(); StartHttpServer(); } } }); task.Wait(); } bool IsRun = true; private ResponseBody UpLoadNc(DeviceList device, object data, CcsRequestBody ccsRequestBody) { CcsRequestBody itemrequestbody = ccsRequestBody.clone() as CcsRequestBody; DeviceOPCUat itemreadopcua = (DeviceOPCUat)device; int runcount = 0; bool tasksleep = true; while (tasksleep) { List itemopcuavalue = itemreadopcua.OpcUa_Read(new List { "/Plc/M1300.0", "/Plc/I37.1" }); if (itemopcuavalue.Where(m => m.Equals("False")).Count() == 0 && itemopcuavalue.Count > 0) // List itemopcuavalue = itemreadopcua.OpcUa_Read(new List { "/Plc/M1300.0"}); if (itemopcuavalue.Where(m => m.Equals("False")).Count() == 0 && itemopcuavalue.Count > 0) { tasksleep = false; } } SFTPDeviceBody sftpBody = DeviceManage.Instance.GetSFTPOne(device.Ip); ResponseBody resBody = ResponseBody.newObject(); //将对象转为文件名数组 //string json = JsonConvert.SerializeObject(data); JArray array = (JArray)JsonConvert.DeserializeObject(data.ToString()); List list = array.ToObject>(); foreach (UploadFileBody uploadBody in list) { string fileName = uploadBody.fileName; DeviceSFTP helper = new DeviceSFTP(sftpBody); try { bool ifcon = helper.Connect(); if (ifcon) { var cc = helper.Put(LocalNcPath + fileName, sftpBody.Path + fileName); helper.Disconnect(); } else { resBody.Msg = "upload failed"; resBody.Code = Constants.RET_FAILURE_CODE; return resBody; } } catch (Exception ex) { YG.Log.Instance.WriteLogAdd($"297-->{ex.Message}"); resBody.Msg = ex.Message; resBody.Code = Constants.RET_FAILURE_CODE; return resBody; } } return resBody; } //选中机床中的NC程序 public bool SelectedNCProgram(DeviceList device, object data, CcsRequestBody ccsRequestBody) { string fileName = data.ObjectToString(); SFTPDeviceBody sftpBody = DeviceManage.Instance.GetSFTPOne(device.Ip); DeviceOPCUat opc = (DeviceOPCUat)device; bool flag = opc.OpcUa_Select(sftpBody.NcExtendPath, fileName); return flag; } //删除机床中的NC程序 public ResponseBody DeleteNCProgram(DeviceList device, object data, CcsRequestBody ccsRequestBody) { ResponseBody resBody = ResponseBody.newObject(); SFTPDeviceBody sftpBody = DeviceManage.Instance.GetSFTPOne(device.Ip); DeviceOPCUat opc = (DeviceOPCUat)device; //将对象转为文件名数组 //string json = JsonConvert.SerializeObject(data); JArray array = (JArray)JsonConvert.DeserializeObject(data.ToString()); List list = array.ToObject>(); foreach (UploadFileBody uploadBody in list) { string fileName = uploadBody.fileName; DeviceSFTP helper = new DeviceSFTP(sftpBody); helper.DeleteFile(sftpBody, fileName); //string status = opc.OpcUa_DeleteFile(sftpBody.Path,fileName); } resBody.Msg = Constants.DEL_PROGRAME_SUCCESS_MSG; resBody.Code = Constants.RET_SUCCESS_CODE; return resBody; } private void callResponse(CcsRequestBody ccsRequestBody, string serverUrl, int code = -1, string msg = "") { if (code == -1) { code = Constants.RET_SUCCESS_CODE; } if (string.IsNullOrWhiteSpace(msg)) { msg = Constants.OPERATE_SUCCESS_MSG; } //如果此操作成功,加入回调任务队列 ccsRequestBody.Data = code + ""; ccsRequestBody.Msg = msg; CommonUtil.ResponseTaskList(ccsRequestBody, serverUrl); } //写入对应的值 public ResponseBody WriteValue(DeviceList device, CcsRequestBody ccsRequestBody, bool isCheck) { string parentKey = ccsRequestBody.BusinessType; ResponseBody resBody = ResponseBody.newObject(); Node parentNode = CommonUtil.GetTargetNode(device.ServerUrl, parentKey); //将读类型赋予设备,供s7协议使用 device.ReadType = parentNode.ReadType; bool isAsk = parentNode.IsAsk; try { //校验条件是否满足 resBody = CheckCondition(parentKey, device, isAsk); if (resBody.Code != 2) { resBody.Msg = Constants.CONDITUIN_CHECK_FAILURE_MSG; resBody.Code = Constants.RET_CONDITUIN_CHECK_FAILURE_CODE; return resBody; } if (device.Dtype.Equals(DeviceType.OPCUa)) { DeviceOPCUat opcua = (DeviceOPCUat)device; bool flag = opcua.OpcUa_WriteValue(parentNode.Address, parentNode.Value); //如果此操作失败返回 if (!flag) { YG.Log.Instance.WriteLogAdd($"------------------>>>>>>>>>>>>>>>>>>>>>>>机床执行程序出现错误"); resBody.Data = Constants.RET_FAILURE_CODE + ""; resBody.Msg = Constants.OPERATE_FAILURE_MSG; return resBody; } } else if (device.Dtype.Equals(DeviceType.PLC_S7)) { DeviceS7 s7 = (DeviceS7)device; //当是智能取或放时 先调智能单元取和放的方法,再执行,如果是柔性产线 需在此处再加一个判断 //取物品 if (parentKey.ToUpper().Equals("FETCHMATERIAL") || parentKey.ToUpper().Equals("PUTMATERIAL")) { #region 取物品 if (parentKey.ToUpper().Equals("FETCHMATERIAL") && ccsRequestBody.Data != null) { if (parentNode.Title.Contains("智能单元")) { int v = ccsRequestBody.Data.ObjectToInt(); s7.DeviceSend("DB3.6", ccsRequestBody.Data.ObjectToString(), parentNode.ReadType); } else if (parentNode.Title.Contains("柔性线")) { int v = ccsRequestBody.Data.ObjectToInt(); s7.DeviceSend("DB200.46", ccsRequestBody.Data.ObjectToString(), parentNode.ReadType); } else if (parentNode.Title.Contains("质量中心")) { int v = ccsRequestBody.Data.ObjectToInt(); s7.DeviceSend("DB200.46", ccsRequestBody.Data.ObjectToString(), parentNode.ReadType); } Thread.Sleep(50); } #endregion #region 放物品 //放物品 if (parentKey.ToUpper().Equals("PUTMATERIAL") && ccsRequestBody.Data != null) { if (parentNode.Title.Contains("智能单元")) { s7.DeviceSend("DB3.8", ccsRequestBody.Data.ObjectToString(), parentNode.ReadType); } else if (parentNode.Title.Contains("柔性线")) { int v = ccsRequestBody.Data.ObjectToInt(); s7.DeviceSend("DB200.48", ccsRequestBody.Data.ObjectToString(), parentNode.ReadType); } else if (parentNode.Title.Contains("质量中心")) { int v = ccsRequestBody.Data.ObjectToInt(); s7.DeviceSend("DB200.48", ccsRequestBody.Data.ObjectToString(), parentNode.ReadType); } Thread.Sleep(50); } #endregion System.Threading.Thread.Sleep(1100); s7.DeviceSend(parentNode.Address, parentNode.Value, parentNode.ReadType); #region 取,放下发动作之后,上报mes //resBody.Code = Constants.RET_SUCCESS_CODE; //resBody.Msg = Constants.OPERATE_SUCCESS_MSG; //如果此操作成功,加入回调任务队列 //ccsRequestBody.Data = resBody.Code + ""; //ccsRequestBody.Msg = resBody.Msg; // CommonUtil.RequestTaskList(ccsRequestBody); #endregion } #region 移动 //移动 if (parentKey.ToUpper().Equals("MOVEMATERIAL") && parentNode.Title.Contains("柔性线") && ccsRequestBody.Data != null) { int v = ccsRequestBody.Data.ObjectToInt(); short pintindex = s7.DeviceRead("DB200.40"); var cc = DeviceConfig.Instance.PointDefaultList.Where(m => m.Train_Index.Equals(pintindex)).FirstOrDefault(); //if (cc.Point.Where(m => m.Equals(ccsRequestBody.Data.ObjectToShort())).Count() == 0) //{ s7.DeviceSend("DB200.48", ccsRequestBody.Data.ObjectToString(), parentNode.ReadType); System.Threading.Thread.Sleep(500); s7.DeviceSend(parentNode.Address, parentNode.Value, parentNode.ReadType); //} //response(ccsRequestBody, Constants.RET_SUCCESS_CODE, Constants.OPERATE_SUCCESS_MSG); } #endregion #region 清洗剂操作 if (parentKey.ToUpper().Equals("CLEAN")) { //if (s7.DeviceRead("DB300.0.7")) // { // s7.DeviceSend("DB300.1.2", true); s7.DeviceSend("DB300.1.2", true, "2"); System.Threading.Thread.Sleep(500); s7.DeviceSend("DB300.1.0", true, "2"); //s7.DeviceSend("DB300.1.0", true); System.Threading.Thread.Sleep(1000); s7.DeviceSend("DB300.1.0", false, "2"); System.Threading.Thread.Sleep(1000); //s7.DeviceSend("DB300.1.0", false); // response(ccsRequestBody, Constants.RET_SUCCESS_CODE, Constants.OPERATE_SUCCESS_MSG); } #endregion #region 三坐标处理 if (parentKey.ToUpper().Equals("TESTWORK")) { TestWorkData testWorkData = Newtonsoft.Json.JsonConvert.DeserializeObject(ccsRequestBody.Data.ToString()); if (testWorkData != null) { var te = testWorkData.WorkId.ReturnBtyesWtitString(40); device.DeviceSend("DB200.52", testWorkData.WorkId.ReturnBtyesWtitString(40)); System.Threading.Thread.Sleep(1100); device.DeviceSend("DB200.92", testWorkData.WorkType.ReturnBtyesWtitString(20)); System.Threading.Thread.Sleep(1000); short mc = 1; device.DeviceSend("DB200.34", mc); System.Threading.Thread.Sleep(1000); mc = 0; device.DeviceSend("DB200.34", mc); } } #endregion #region 打标 if (parentKey.ToUpper().Equals("PRINT")) { try { DeviceList devicesocket = DeviceManage.Instance.deviceList.Where(m => m.Key.Equals("192.168.170.76:8074")).FirstOrDefault().Value; devicesocket.DeviceSend(ccsRequestBody.Data); short mc = 1; mc = 0; device.DeviceSend("DB200.24", mc); System.Threading.Thread.Sleep(1000); mc = 1; s7.DeviceSend("DB200.28", mc, "1"); System.Threading.Thread.Sleep(1000); mc = 0; //s7.DeviceSend("DB200.28", mc); s7.DeviceSend("DB200.28", mc, "1"); } catch (Exception ex) { YG.Log.Instance.WriteLogAdd($"498-->{ex.Message}"); //response(ccsRequestBody, Constants.RET_CONDITUIN_CHECK_FAILURE_CODE, Constants.CONDITUIN_CHECK_FAILURE_MSG); YG.Log.Instance.WriteLogAdd($"{ex.Message}"); } } #endregion #region RFID读写 if (parentKey.ToUpper().Equals("RFIDREAD")) { try { //List testWorkData = Newtonsoft.Json.JsonConvert.DeserializeObject>(ccsRequestBody.Data.ToString()); //var te = ccsRequestBody.Data.ToString().ReturnBtyesWtitString(256); ////device.DeviceSend("DB200.938", testWorkData.WorkId.ReturnBtyesWtitString(40)); ////System.Threading.Thread.Sleep(1100); ////device.DeviceSend("DB200.92", testWorkData.WorkType.ReturnBtyesWtitString(20)); //short mc = 1; //device.DeviceSend("DB200.112", mc); //System.Threading.Thread.Sleep(1000); //mc = 0; //device.DeviceSend("DB200.112", mc); //string rfidvalue = s7.DeviceRead("DB200.116.0", "5", 256); ccsRequestBody.IsCallBackFlag = 0; resBody.Data = DeviceRfid.Instance.DeviceRead($"{ccsRequestBody.Url}:{ccsRequestBody.Port}").Json_SerializeObject(); YG.Log.Instance.WriteLogAdd($"RFIDREAD-->{resBody.Json_SerializeObject()}"); } catch (Exception ex) { YG.Log.Instance.WriteLogAdd($"549--->{ex.Message}"); } } if (parentKey.ToUpper().Equals("RFIDWRITE")) { try { List testWorkData = Newtonsoft.Json.JsonConvert.DeserializeObject>(ccsRequestBody.Data.ToString()); ////TestWorkData testWorkData = Newtonsoft.Json.JsonConvert.DeserializeObject(ccsRequestBody.Data.ToString()); //device.DeviceSend("DB200.372.0", ccsRequestBody.Data.ToString().ReturnBtyesWtitString(256)); //short mc = 1; //device.DeviceSend("DB200.114", mc); //System.Threading.Thread.Sleep(1000); //mc = 0; //device.DeviceSend("DB200.114", mc); //YG.Log.Instance.WriteLogAdd($"RFIDWRITE-->"); ccsRequestBody.IsCallBackFlag = 0; resBody.Data = "RFID写入结果->" + DeviceRfid.Instance.DeviceSend(testWorkData, $"{ccsRequestBody.Url}:{ccsRequestBody.Port}").Json_SerializeObject(); YG.Log.Instance.WriteLogAdd($"RFIDREAD-->{resBody.Json_SerializeObject()}"); } catch (Exception ex) { YG.Log.Instance.WriteLogAdd($"567--->{ex.Message}"); } } #endregion } } catch (Exception ex) { YG.Log.Instance.WriteLogAdd($"508-->{ex.Message}"); resBody.Code = Constants.RET_FAILURE_CODE; resBody.Msg = ex.Message; return resBody; } resBody.Code = Constants.RET_SUCCESS_CODE; resBody.Msg = Constants.OPERATE_SUCCESS_MSG; return resBody; } public ResponseBody CheckCondition(string parentKey, DeviceList device, bool isAsk) { ResponseBody resBody = ResponseBody.newObject(); List list = CommonUtil.GetTargetList(device.ServerUrl, parentKey); if (list.Count == 0) { resBody.Code = Constants.RET_CONDITUIN_CHECK_SUCCESS_CODE; resBody.Msg = Constants.CONDITUIN_CHECK_SUCCESS_MSG; return resBody; } try { if (device.Dtype.Equals(DeviceType.OPCUa)) { DeviceOPCUat opcua = (DeviceOPCUat)device; List nodeIdStrings = new List(); foreach (Node nd in list) { nodeIdStrings.Add(nd.Address); } List retValueList = opcua.OpcUa_Read(nodeIdStrings); //比较目标值是否一致 for (int i = 0; i < list.Count; i++) { Node cNode = list[i]; if (!retValueList[i].Equals(cNode.TargetValue)) { Node parentNode = CommonUtil.GetTargetNode(device.ServerUrl, parentKey); resBody.Code = Constants.RET_CONDITUIN_CHECK_FAILURE_CODE; resBody.Msg = cNode.Title + "状态不符合" + parentNode.Title + "条件。"; break; } } } else if (device.Dtype.Equals(DeviceType.PLC_S7)) { DeviceS7 s7 = (DeviceS7)device; foreach (Node nd in list) { string respvalue = ""; if (nd == null || nd.Address.StringIsEmpty()) { Log.Instance.WriteLogAdd($"593-->为空->{s7.DeviceName}"); } respvalue = s7.DeviceRead(nd.Address.Trim(), nd.ReadType); int itemnumber = nd.TargetValue.StringToInt(); if (itemnumber < 0) { if (respvalue.Equals(Math.Abs(itemnumber).ToString())) { Node parentNode = CommonUtil.GetTargetNode(device.ServerUrl, parentKey); resBody.Code = Constants.RET_CONDITUIN_CHECK_FAILURE_CODE; resBody.Msg = nd.Title + "状态不符合" + parentNode.Title + "条件。"; break; } } else if (!respvalue.Equals(nd.TargetValue)) { Node parentNode = CommonUtil.GetTargetNode(device.ServerUrl, parentKey); resBody.Code = Constants.RET_CONDITUIN_CHECK_FAILURE_CODE; resBody.Msg = nd.Title + "状态不符合" + parentNode.Title + "条件。"; break; } } } } catch (Exception ex) { YG.Log.Instance.WriteLogAdd($"582-->{ex.Message}"); resBody.Code = Constants.RET_CONDITUIN_CHECK_FAILURE_CODE; resBody.Msg = ex.Message; return resBody; } if (resBody.Code == 1) { resBody.Code = Constants.RET_CONDITUIN_CHECK_SUCCESS_CODE; resBody.Msg = Constants.CONDITUIN_CHECK_SUCCESS_MSG; } return resBody; } private string OperAsk(Node parentNode, ModbusClient server, int times) { string ret = RETVAL; bool isContinue = true; for (int n = 0; n < times; n++) { if (parentNode != null) { string[] adresses = (parentNode.Address).Split(util.CommonUtil.SEPLIT_CHAR); string[] targetValues = (parentNode.TargetValue).Split(util.CommonUtil.SEPLIT_CHAR); List nodeIdStrings = new List(); //foreach (string row in adresses) //{ // nodeIdStrings.Add(new NodeId(row, (ushort)2).ToString()); //} //List readValueList = server.ReadValues(nodeIdStrings); //for (int i = 0; i < readValueList.Count; i++) //{ // if (targetValues[i].ToLower().Equals(readValueList[i].ToLower())) // { // //ret = parentNode.Title + "当前已是操作状态,无需重复操作。"; // isContinue = false; // break; // } //} } Thread.Sleep(1000 * 5); if (!isContinue) { break; } } return ret; } //采集信息 public bool GetDeviceCollectData() { foreach (ConnectDeviceBody body in DeviceManage.Instance.GetConnectDeviceList()) { try { DeviceList device = DeviceManage.Instance.GetOne(body.ServerUrl); //read组的配置 List readNodeList = CommonUtil.GetTargetList(device.ServerUrl, "read"); CollectDataBody deviceRedisState = new CollectDataBody(); //根据配置里边的read组配置, 把读到的值放到这个里边 List readNodeValueStrings = new List(); if (device.Dtype.Equals(DeviceType.OPCUa)) { try { DeviceOPCUat opcua = (DeviceOPCUat)device; //read组配置的地址列表 List readNodeAddressStrings = new List(); foreach (Node nd in readNodeList) { readNodeAddressStrings.Add(nd.Address); } Thread.Sleep(20); readNodeValueStrings = opcua.OpcUa_Read(readNodeAddressStrings); } catch (Exception exxx) { YG.Log.Instance.WriteLogAdd($"692-->{exxx.Message}"); } } else if (device.Dtype.Equals(DeviceType.PLC_S7)) { DeviceS7 s7 = (DeviceS7)device; try { foreach (Node nd in readNodeList) { if (nd == null || nd.Address.StringIsEmpty()) { Log.Instance.WriteLogAdd($"709-->为空->{s7.DeviceName}"); } readNodeValueStrings.Add(s7.DeviceRead(nd.Address, nd.ReadType)); Thread.Sleep(20); } } catch (Exception exxx) { YG.Log.Instance.WriteLogAdd($"706-->{exxx.Message}"); } } //将结果值赋给节点 for (int i = 0; i < readNodeList.Count; i++) { try { if (readNodeValueStrings.Count > 0) { Node readValNode = readNodeList[i]; readValNode.Value = readNodeValueStrings[i]; } } catch (Exception exxx) { YG.Log.Instance.WriteLogAdd($"719-->{exxx.Message}"); } } //反射赋值 Type t = deviceRedisState.GetType(); foreach (PropertyInfo pi in t.GetProperties()) { try { string name = pi.Name;//获得属性的名字,后面就可以根据名字判断来进行些自己想要的操作 if (pi.Name.Equals("AllowFetchMaterial")) { } foreach (Node nd in readNodeList) { if (nd.Key == name) { if (nd.IsBinary) { //处理二进制值,赋给对象 pi.SetValue(deviceRedisState, CommonUtil.GetBinaryBit(Convert.ToInt32(nd.Value), nd.StartPos, nd.EndPos), null); } else {//主程序取名称 if (name == "MainProgNo" && !string.IsNullOrEmpty(nd.Value)) { string[] mainProgNoArray = nd.Value.Split('/'); string mainProgNo = mainProgNoArray[mainProgNoArray.Length - 1]; mainProgNo = mainProgNo.StartsWith("_") ? mainProgNo.Substring(1, mainProgNo.Length - 1) : mainProgNo; pi.SetValue(deviceRedisState, mainProgNo, null); } else if (name == "SpActSpeed" && !string.IsNullOrEmpty(nd.Value)) { pi.SetValue(deviceRedisState, (Convert.ToInt32(Convert.ToDouble(nd.Value)) + ""), null); } else { pi.SetValue(deviceRedisState, nd.Value, null);//给对象赋值 } } } } } catch (Exception exx) { YG.Log.Instance.WriteLogAdd($"764-->{exx.Message}"); } } try { deviceRedisState.NowDate = string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now); string jsonData = JsonConvert.SerializeObject(deviceRedisState); ServiceStackRedisHelper.SetValue(device.ServerUrl, jsonData.ToString()); } catch (Exception exs) { YG.Log.Instance.WriteLogAdd($"916------>>{exs.Message}"); } //回调请求 每隔5秒调一次 int currentSencond = DateTime.Now.Second; // if (currentSencond % 3 == 0) { try { CommonUtil.CallBackRequest(device); } catch(Exception exs) { YG.Log.Instance.WriteLogAdd($"922------>>{exs.Message}"); } } } catch (Exception ex) { YG.Log.Instance.WriteLogAdd($"776-->{ex.Message}"); return false; } } return true; } } public class Servlet { public virtual void onGet(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response, string info) { } public virtual void onPost(System.Net.HttpListenerRequest request, System.Net.HttpListenerResponse response) { } public virtual void onCreate() { } } public class MyServlet : Servlet { public override void onCreate() { base.onCreate(); } public override void onGet(HttpListenerRequest request, HttpListenerResponse response, string info) { byte[] buffer = Encoding.UTF8.GetBytes(info); System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); } public override void onPost(HttpListenerRequest request, HttpListenerResponse response) { Console.WriteLine("POST:" + request.Url); byte[] res = Encoding.UTF8.GetBytes("OK"); response.OutputStream.Write(res, 0, res.Length); } } }