using DBFactory; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading; namespace WcfControlMonitorLib { public class IHttpHelperMonitor { public static List HttpPostRequest = new List(); public static DBOperator dbo = CStaticClass.dbo; public static StringBuilder sql = new StringBuilder(); public static DataView dv = new DataView(); public static void createHttpPostRequest(bool bl) { if (bl) { try { HttpPostRequest = new List(); HttpPostRequest.Add(new MyHttp() { HttpPostListener = new HttpListener(), HttpPostUrl = CStaticClass.AGV_Receive_HTTPURL }); foreach (var hpr in HttpPostRequest) { try { string url = hpr.HttpPostUrl; hpr.HttpPostListener.Prefixes.Add(url); hpr.HttpPostListener.Start(); Thread ThrednHttpPostRequest = new Thread(new ParameterizedThreadStart(HttpPostRequestHandle)) { IsBackground = true }; ThrednHttpPostRequest.Start(hpr); } catch (Exception ex) { //new DisplaySet().AddListBoxItem("", ex.Message); } //new DisplaySet().AddListBoxItem("", "启动监听成功:" + hpr.HttpPostUrl); } } catch (Exception ex) { //new DisplaySet().AddListBoxItem("", "启动监听失败:" + ex.Message); } } else { try { foreach (var hpr in HttpPostRequest) { hpr.HttpPostListener.Stop(); hpr.HttpPostListener.Prefixes.Clear(); hpr.HttpPostListener.Close(); hpr.HttpPostListener = null; //new DisplaySet().AddListBoxItem("", "关闭监听成功:" + hpr.HttpPostUrl); } } catch (Exception ex) { //new DisplaySet().AddListBoxItem("", "关闭监听失败:" + ex.Message); } } } /// /// 获取监听数据 /// /// private static void HttpPostRequestHandle(object myHttp) { while (true) { try { if (myHttp is MyHttp) { HttpListenerContext rContext = (myHttp as MyHttp).HttpPostListener.GetContext(); Thread thread = new Thread(new ParameterizedThreadStart((context) => { #region HttpListenerContext MyContext = (HttpListenerContext)context; string RecieveBuffer = string.Empty; string en1 = MyContext.Request.ContentEncoding.EncodingName; string ContentType = MyContext.Request.ContentType; using (Stream myRequestStream = MyContext.Request.InputStream) { using (StreamReader myStreamReader = new StreamReader(myRequestStream, Encoding.UTF8)) { RecieveBuffer = myStreamReader.ReadToEnd(); myStreamReader.Close(); myRequestStream.Close(); } } MyContext.Response.StatusCode = 200; ////MyContext.Response.Headers.Add("Access-Control-Allow-Origin", "*"); MyContext.Response.ContentType = "application/json"; MyContext.Response.ContentEncoding = Encoding.UTF8; string url = MyContext.Request.Url.ToString(); string repose = string.Empty;//方法返回异常 string InterfaceNote = string.Empty;//方法注释 string retjson = string.Empty;//返回JSON串 string InterfaceFlow = " AGV==>> WMS";//接口方向 string InterfaceName = string.Empty; //接口访问方法地址信息 string[] InterfaceURL = url.Split('/').Where(c => !string.IsNullOrEmpty(c)).ToArray(); //固定接收地址 string[] receiveURL = CStaticClass.AGV_Receive_HTTPURL.Split('/').Where(c => !string.IsNullOrEmpty(c)).ToArray(); int n = 0;//固定地址层级 for (int i = 0; i < InterfaceURL.Length; i++) { if (InterfaceURL[i] == receiveURL[receiveURL.Length - 1]) { n = i; break; } } for (int i = n + 1; i < InterfaceURL.Length; i++) { InterfaceName = InterfaceName + ">>" + InterfaceURL[i]; } InterfaceName = InterfaceName.TrimStart('>'); #endregion switch (InterfaceName.ToUpper()) { #region 测试 case "TEST": #region InterfaceNote = "测试接口"; InterfaceFlow = "WMS ==>> WCS"; retjson = "{\"code\":\"0\",\"message\":\"sucess\",\"data\":[{\"id\":\"485484115282370560\",\"orderId\":\"485823953844051968\",\"materialNo\":\"F03C.K38.784\",\"storageLocation\":\"M002\",\"storageBin\":\"A280330\",\"quantity\":\"2\",\"materialName\":\"10606无油衬套\",\"description\":\"C-MUBZ10-16\",\"timeStamp\":\"2022-09-02 16:21:00\"}]}"; break; #endregion case "V1>>MOVEPALLET": InterfaceNote = "测试--下发AGV任务"; string taskId = GetReceiveValues(RecieveBuffer, "relatedOrder"); JObject data = new JObject(); data.Add(new JProperty("missionId", taskId));//托盘编码 JObject ob = new JObject(); ob.Add(new JProperty("msg", "操作成功")); ob.Add(new JProperty("code", 200)); ob.Add(new JProperty("data", data)); retjson = JsonConvert.DeserializeObject(ob.ToString()).ToString(); break; case "LOGIN": JObject obToken = new JObject(); obToken.Add(new JProperty("msg", "操作成功")); obToken.Add(new JProperty("code", 200)); obToken.Add(new JProperty("token", Guid.NewGuid().ToString())); retjson = JsonConvert.DeserializeObject(obToken.ToString()).ToString(); break; #endregion #region 正式 case "AGVTASKFEEDBACK": InterfaceNote = "AGV任务信息反馈"; LogOperation(InterfaceName, RecieveBuffer, retjson); retjson = AGVTaskFeedback(RecieveBuffer); break; #endregion default: #region InterfaceNote = ""; JObject objMis = new JObject(); objMis.Add(new JProperty("method", InterfaceName)); objMis.Add(new JProperty("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))); JObject objDate = new JObject(); objDate.Add(new JProperty("code", "200"));//库号 objDate.Add(new JProperty("msg", "无效方法"));//入库输送站台编号 objDate.Add(new JProperty("taskId", ""));//容器编号 objMis.Add(new JProperty("data", objDate)); retjson = JsonConvert.DeserializeObject(objMis.ToString()).ToString(); break; #endregion } #region 接口日志记录 if (string.IsNullOrEmpty(InterfaceNote)) { InterfaceNote = InterfaceNote; LogOperation(InterfaceName, RecieveBuffer, retjson); } #endregion 接口日志记录 byte[] SendBuffer = System.Text.Encoding.UTF8.GetBytes(retjson); MyContext.Response.ContentLength64 = SendBuffer.Length; using (var myOutputStream = MyContext.Response.OutputStream) { myOutputStream.Write(SendBuffer, 0, SendBuffer.Length); myOutputStream.Close(); } })) { IsBackground = true }; thread.Start(rContext); } } catch (Exception) { } Thread.Sleep(50); } } /// /// AGV任务信息反馈 /// /// /// private static string AGVTaskFeedback(string recieveBuffer) { string retJson = string.Empty; try { // { // "taskId":1223, //任务Id //"relatedOrder":"xxxx", //"status":"completed", //completed(成功) ,failed(失败),outbin(离开起始点),redirect //"msg":"msg", //异常消息 //"dst":"A-01-01", // ⽬标库位 //"alias":"alias", //"robot":"robot-1" //运⾏⻋的code //} string taskId = GetReceiveValues(recieveBuffer, "taskId");//主任务id //string relatedOrder = GetReceiveValues(recieveBuffer, "relatedOrder");//订单号/子任务 id string status = GetReceiveValues(recieveBuffer, "status");//状态 completed(成功) ,failed(失败),outbin(离开起始点),redirect string msg = GetReceiveValues(recieveBuffer, "msg");//异常消息 //string robot = GetReceiveValues(recieveBuffer, "robot");//运⾏⻋的code //接收到AGV 任务反馈,根据AGV任务号,修改 AGV_task 表和 子任务表信息 sql.Remove(0, sql.Length); sql.Append("SELECT * FROM AGV_TASK WHERE REMARK = ").Append(taskId); dv = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView; if (dv.Count > 0) { //任务状态:0等待执行;AGV控制台更新,7AGV已经接受,10开始分配执行,999执行完成;错误码待定 //Started:任务启动 Failed:任务失败 Done:任务完成 RackUp:货架抬起 RackDown:货架放下 int AGV_TASK_STATUS = 0; switch (status) { case "TargetOutDone"://成功 case "Done"://成功 AGV_TASK_STATUS = 999; break; case "Failed"://失败 AGV_TASK_STATUS = 30; break; case "RackUp"://离开起始点 AGV_TASK_STATUS = 980; string sqlStr = string.Format("select * from AGV_TASK where REMARK = '{0}'", taskId); DataView dataView = dbo.ExceSQL(sqlStr).Tables[0].DefaultView; if (dataView != null && dataView.Count > 0) { int device_code = Convert.ToInt32(dataView[0]["START_DEVICE_CODE"]); if (device_code == 12029 || device_code == 12033 || device_code == 12035 || device_code == 12037) { automaticTask(device_code, "12070"); } } break; //case "redirect"://更改 // AGV_TASK_STATUS = 10; break; default: AGV_TASK_STATUS = 30;//异常 break; } sql.Remove(0, sql.Length); //sql.Append("UPDATE AGV_TASK SET AGV_TASK_STATUS = " + AGV_TASK_STATUS + " ,AGV_CODE = " + robot + " where FID = " + taskId + " "); sql.Append("UPDATE AGV_TASK SET AGV_TASK_STATUS = " + AGV_TASK_STATUS + " where REMARK = '" + taskId + "' "); int exNum = dbo.ExecuteSql(sql.ToString()); if (AGV_TASK_STATUS == 999) { //完成任务 } JObject data = new JObject(); data.Add(new JProperty("missionId", taskId));//托盘编码 JObject ob = new JObject(); if (exNum > 0) { ob.Add(new JProperty("msg", "操作成功")); ob.Add(new JProperty("code", 200)); } else { ob.Add(new JProperty("msg", "操作失败")); ob.Add(new JProperty("code", 500)); } ob.Add(new JProperty("data", data)); retJson = JsonConvert.DeserializeObject(ob.ToString()).ToString(); } else { JObject ob = new JObject(); ob.Add(new JProperty("msg", "操作失败")); ob.Add(new JProperty("code", 500)); retJson = JsonConvert.DeserializeObject(ob.ToString()).ToString(); } return retJson; } catch (Exception ex) { return retJson; } } /// /// AGV 任务下发 /// public static bool AGVTaskRelease(string fid) { bool bl = false; string reqJson = string.Empty; try { string InterfaceAdd = CStaticClass.AGV_Upper_URL + "v1/movePallet";//请求路径 StringBuilder sql = new StringBuilder(); sql.Remove(0, sql.Length); sql.Append("SELECT * FROM AGV_TASK WHERE AGV_TASK_STATUS = 0 and fid = " + fid); dv = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView; for (int i = 0; i < dv.Count; i++) { StringBuilder sDor = new StringBuilder(); #region json //起始位置 JObject takeFrom = new JObject(); takeFrom.Add(new JProperty("code", dv[i]["START_DEVICE_CODE"]));//货位编码 takeFrom.Add(new JProperty("height", 0));//库位地点高度 takeFrom.Add(new JProperty("useAlias", true));//是否使用别名 //目标位置 JObject transferTo = new JObject(); transferTo.Add(new JProperty("code", dv[i]["FINISH_DEVICE_CODE"]));//货位编码 transferTo.Add(new JProperty("height", 0));//库位地点高度 transferTo.Add(new JProperty("useAlias", true));//是否使用别名 //货物信息 JObject cargo = new JObject(); //cargo.Add(new JProperty("pallet", dv[i]["PALLET_BARCODE"]));//托盘编码 //cargo.Add(new JProperty("palletHeight", 0));//托盘高度 //cargo.Add(new JProperty("palletLength", 0));//托盘长度 //cargo.Add(new JProperty("palletWidth", 0));//托盘宽度 //cargo.Add(new JProperty("height", 0));//总高度 cargo.Add(new JProperty("type", "Pallet"));//总高度 string mapID = string.Empty;//地图编码 switch (dv[i]["START_DEVICE_CODE2"].ToString()) { case "50001": mapID = "floor2"; break; case "50002": mapID = "floor1"; break; case "50003": mapID = "floor3"; break; } JObject objMis = new JObject(); objMis.Add(new JProperty("floor", mapID));//地图编码 objMis.Add(new JProperty("takeFrom", dv[i]["START_DEVICE_CODE"])); objMis.Add(new JProperty("transferTo", dv[i]["FINISH_DEVICE_CODE"])); objMis.Add(new JProperty("cargo", cargo)); objMis.Add(new JProperty("relatedOrder", dv[i]["REMARK"]));//单号 string json = JsonConvert.DeserializeObject(objMis.ToString()).ToString(); #endregion reqJson = JsonConvert.DeserializeObject(objMis.ToString()).ToString(); LogOperation("AGVTaskRelease", "请求地址", InterfaceAdd); string mode = CommonClassLib.AppSettings.GetValue("Mode"); if (mode != "test") { string retJson = PostJson(InterfaceAdd, reqJson); string code = GetReceiveValues(retJson, "code"); string msg = GetReceiveValues(retJson, "msg"); if (code == "200") { bl = true; } else if (code == "601")//token 过期 { GetAGVToKen(); } #region 添加接口日志 及界面显示 LogOperation("AGVTaskRelease", reqJson, retJson); #endregion } } return bl; } catch (Exception ex) { LogOperation("AGVTaskRelease", reqJson, ex.Message); return false; } } /// /// 向AGV 获取 token /// public static void GetAGVToKen() { string reqJson = string.Empty; try { //http://ip:port/prod-api/api/v1/movePallet //http://ip:port/prod-api/api/login string InterfaceAdd = CStaticClass.AGV_Upper_URL + "login";//请求路径 StringBuilder sql = new StringBuilder(); sql.Remove(0, sql.Length); sql.Append("SELECT * FROM AGV_TASK WHERE AGV_TASK_STATUS = 0 "); dv = dbo.ExceSQL(sql.ToString()).Tables[0].DefaultView; #region json JObject objMis = new JObject(); //objMis.Add(new JProperty("taskId", UtilityBLL.GetUuid()));//接口交互 任务号 谁发起,谁生成 objMis.Add(new JProperty("username", CStaticClass.AGV_username));//接口交互 任务号 objMis.Add(new JProperty("password", CStaticClass.AGV_password)); #endregion reqJson = JsonConvert.DeserializeObject(objMis.ToString()).ToString(); string mode = CommonClassLib.AppSettings.GetValue("Mode"); if (mode != "test") { string retJson = PostJson(InterfaceAdd, reqJson); string code = GetReceiveValues(retJson, "code"); //状态码 200 成功 if (code == "200") { string AGV_token = GetReceiveValues(retJson, "token"); string AGV_token_LastTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm"); //保存获取到的 token 值 CommonClassLib.AppSettings.SetValue("AGV_token", AGV_token); CommonClassLib.AppSettings.SetValue("AGV_token_LastTime", AGV_token_LastTime); CStaticClass.AGV_token = AGV_token;//AGV_token CStaticClass.AGV_token_LastTime = AGV_token_LastTime;//AGV_token 上次请求时间 } #region 添加接口日志 及界面显示 LogOperation("AGVTaskRelease", reqJson, retJson); #endregion } } catch (Exception ex) { LogOperation("AGVTaskRelease", reqJson, ex.Message); } } /// /// http传参 设置header值 /// /// 路径 /// 请求JSON body /// 类别 /// /// public static string PostJson(string url, string strPost, string contentType = "application/json;charset=utf-8") { string retJson = string.Empty; try { //string reqCode = UtilityBLL.GetReceiveValues(strPost, "reqCode"); string reqCode = ""; Hashtable head = new Hashtable(); //head.Add("appKey", Global.appKey); //head.Add("requestPlan", Global.requestPlan); //head.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); //head.Add("version", Global.version); //head.Add("httpVersion", Global.httpVersion); //head.Add("sign", utilityBLL.GenerateMD5(Global.appSecret + reqCode)); //head.Add("sign", "A71253A5731E6261ADE4E23283AF2B28"); LogOperation("AGVTaskRelease", CStaticClass.AGV_token, retJson); head.Add("Authorization", CStaticClass.AGV_token); retJson = Http(url, "POST", contentType, head, strPost); return retJson; //string code = UtilityBLL.GetReceiveValues(retJson, "data,code"); #region 修改前 //string code = GetReceiveValues(retJson, "code"); //if (code == "0" || code == "1" || code == "00" || code == "01" || code == "99" || code == "200") //{ // return retJson; //} //else //{ // reqCode = GetReceiveValues(strPost, "reqCode"); // retJson = JsonConvert.SerializeObject(new { reqCode = reqCode, code = 200, message = retJson }); // return retJson; //} #endregion //if (retJson == "操作超时") //{ // reqCode = utilityBLL.getReceiveValues(strPost, "reqCode"); // retJson = JsonConvert.SerializeObject(new { reqCode = reqCode, code = 200, message = retJson }); //}else if(retJson == "远程服务器返回错误: (500) 内部服务器错误。") //{ // reqCode = utilityBLL.getReceiveValues(strPost, "reqCode"); // retJson = JsonConvert.SerializeObject(new { reqCode = reqCode, code = 200, message = retJson }); //} } catch (Exception ex) { string reqCode = GetReceiveValues(strPost, "strPost"); return JsonConvert.SerializeObject(new { reqCode = reqCode, code = 200, message = ex.Message }); } } /// /// 不做catch处理,需要在外部做 /// /// /// 默认GET,空则补充为GET /// 默认json,空则补充为json /// 请求头部 /// 请求body内容 /// public static string Http(string url, string method = "GET", string contenttype = "application/json;charset=utf-8", Hashtable header = null, string data = null) { string json = string.Empty; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = string.IsNullOrEmpty(method) ? "GET" : method; request.ContentLength = 0; request.KeepAlive = false; //设置不建立持久性连接连接 request.ProtocolVersion = HttpVersion.Version10; //http的版本有2个,一个是1.0,一个是1.1 具体更具实际情况测试替换 request.ContentType = string.IsNullOrEmpty(contenttype) ? "application/json;charset=utf-8" : contenttype; Encoding encoding = Encoding.UTF8; //request.ContentLength = buffer.Length; //request.GetRequestStream().Write(buffer, 0, buffer.Length); if (header != null) { foreach (var i in header.Keys) { request.Headers.Add(i.ToString(), header[i].ToString()); } } if (!string.IsNullOrEmpty(data)) { //request.Accept = "text/html, application/xhtml+xml, */*"; byte[] buffer = encoding.GetBytes(data.ToString()); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); request.Timeout = 1000 * 60; Stream ResponseStream = response.GetResponseStream(); StreamReader StreamReader = new StreamReader(ResponseStream, Encoding.GetEncoding("utf-8")); json = StreamReader.ReadToEnd(); StreamReader.Close(); ResponseStream.Close(); return json; } catch (Exception ex) { return json = ex.Message; } } /// /// 获取json中指定Key的value值 不能取集合中数据 /// /// json串 /// json节点 /// public static string GetReceiveValues(string recieveBuffer, string key) { try { key = key.Replace(" ", ""); string[] keys = key.Split(','); string resMag = recieveBuffer; if (!string.IsNullOrEmpty(recieveBuffer)) { for (int i = 0; i < keys.Count(); i++) { JObject obj = Newtonsoft.Json.Linq.JObject.Parse(resMag); resMag = obj[keys[i]].ToString(); } } return resMag; } catch (Exception ex) { //LogHelper.ErrorLog(ex); return ""; } } /// /// 创建接口访问日志 /// /// 方法名 /// 请求JSON /// 返回JSON public static void LogOperation(string methodName, string requestJson, string returnJson) { try { string path = System.Environment.CurrentDirectory; string newPath = path + "\\" + methodName + "\\"; if (!System.IO.Directory.Exists(newPath)) { System.IO.Directory.CreateDirectory(newPath); } string fName = newPath + DateTime.Now.ToString("yyyy-MM-dd") + ".log"; FileInfo fileInfo = new FileInfo(fName); if (fileInfo.Exists == false) { using (StreamWriter sw = fileInfo.CreateText()) { sw.WriteLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")); sw.WriteLine("请求:" + requestJson.Replace("\r\n", "").Replace("\n", "")); sw.WriteLine("反馈:" + returnJson.Replace("\r\n", "").Replace("\n", "")); sw.WriteLine(); sw.Flush(); sw.Close(); } FilesDelete(fileInfo.DirectoryName); } else { using (StreamWriter sw = fileInfo.AppendText()) { sw.WriteLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")); sw.WriteLine("请求:" + requestJson.Replace("\r\n", "").Replace("\n", "")); sw.WriteLine("反馈:" + returnJson.Replace("\r\n", "").Replace("\n", "")); sw.WriteLine(); sw.Flush(); sw.Close(); } } } catch (Exception) { } } private static void FilesDelete(string delURL, string suffix = ".log", int days = 30) { try { DirectoryInfo root = new DirectoryInfo(delURL); FileInfo[] files = root.GetFiles(); if (files.Length <= 10) { return; } foreach (FileInfo fi in files) { if (fi.Extension.ToUpper() == suffix.ToUpper()) { DateTime createTime = fi.CreationTime; DateTime newTime = DateTime.Now.AddDays(-1); if (Convert.ToDateTime(fi.CreationTime) <= DateTime.Now.AddDays(-days)) { createTime = fi.CreationTime; fi.Delete(); } } } } catch (Exception) { throw; } } public class MyHttp { /// /// 侦听器 /// public HttpListener HttpPostListener { get; set; } /// /// URL地址 /// public string HttpPostUrl { get; set; } } public static void automaticTask(int stVal, string endVal) { string dtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); CCommonFunction ccf = new CCommonFunction(); int AutoManageIdx = ccf.GetTempManageIdx(); //插入临时调度任务T_Manage_Task(监控下的调度任务): string Sql = "insert into T_Manage_Task(FID,FPALLETBARCODE,FCONTROLTASKTYPE,F_ManageTaskKindIndex,FSTARTWAREHOUSE,FSTARTDEVICE,FSTARTCELL," + "FENDWAREHOUSE,FENDDEVICE,FENDCELL,FLANEWAY,FSTACK,FUseAwayFork,FBEGTIME) " + "values(" + AutoManageIdx + ",'" + "PP" + stVal.ToString() + "','4',2,'1','" + stVal + "','-','1','" + endVal + "','-', '-' ,'','-','" + dtime + "')";//20101028 if (dbo.ExecuteSql(Sql) > 0) { CommonClassLib.CCarryConvert.WriteDarkCasket("OPCClient", "生成自动任务成功", stVal.ToString(), $"生成{stVal}到{endVal} 任务成功!"); } } } }