/// <summary> /// 通讯状态观察 /// </summary> private void CommunicationObser(object sender, System.Timers.ElapsedEventArgs e) { try { communicationobserve_timer.Enabled = false; //接收超时,进行重新连接 if (LastConnectLong > 3) { LogHelper.WriteLog("重连" + DeviceID.ToString() + "号IO设备"); ReConnect(); } if (LastRecLong > 2) { IODeviceInfo IOInfo = new IODeviceInfo(); IOInfo.ID = this.DeviceID; DelegateState.InvokeDispatchStateEvent(this.DeviceID.ToString() + "号IO设备掉线,重新尝试连接..."); //通知调度程序 小车已经掉线 IOInfo.bIsCommBreak = true; DelegateState.InvokeIOFeedBackEvent(IOInfo); } } catch (Exception ex) { DelegateState.InvokeDispatchStateEvent(this.DeviceID.ToString() + "号IO设备,观察线程异常"); LogHelper.WriteErrorLog(ex); } finally { if (!IsStop) { communicationobserve_timer.Enabled = true; } } }
/// <summary> /// 通讯状态观察 /// </summary> private void CommunicationObser(object sender, System.Timers.ElapsedEventArgs e) { try { communicationobserve_timer.Enabled = false; //先判断小车是否已经掉线 if (LastRecLong > 2) { //如果接受消息时间已经大于2秒,则认为车子掉线了。 DelegateState.InvokeDispatchStateEvent(this.DeviceID.ToString() + "车,已经掉线,将在1秒后重新尝试连接..."); //通知调度程序 小车已经掉线 CarBaseStateInfo car = new CarBaseStateInfo(); car.bIsCommBreak = true; car.AgvID = this.DeviceID; DelegateState.InvokeCarFeedbackEvent(car); if (LastConnectLong > 3) { //如果车子掉线且连接时间超过3秒则需要重连 LogHelper.WriteLog("重连小车" + DeviceID.ToString()); ReConnect(); } } } catch (Exception ex) { DelegateState.InvokeDispatchStateEvent(this.DeviceID.ToString() + "车,观察线程异常"); LogHelper.WriteErrorLog(ex); } finally { { communicationobserve_timer.Enabled = true; } } }
public bool ExternelServerStart() { try { DelegateState.InvokeDispatchStateEvent("正在初始化外围服务..."); string FILEPATH = Application.StartupPath + @"/sysconfig.xml"; Hashtable htServer = XMLClass.GetXMLByParentNode(FILEPATH, XMLConstClass.NODE_SERVER); string port = "2018"; string maxclient = "200"; string rcvtimeout = "100"; string sendtimeout = "100"; string buffersize = "128"; if (htServer.Contains(XMLConstClass.PORT)) { port = htServer[XMLConstClass.PORT].ToString(); } if (htServer.Contains(XMLConstClass.MAXCONNECTCOUNT)) { maxclient = htServer[XMLConstClass.MAXCONNECTCOUNT].ToString(); } if (htServer.Contains(XMLConstClass.RECTIMEOUT)) { rcvtimeout = htServer[XMLConstClass.RECTIMEOUT].ToString(); } if (htServer.Contains(XMLConstClass.SENDTIMEOUT)) { sendtimeout = htServer[XMLConstClass.SENDTIMEOUT].ToString(); } if (htServer.Contains(XMLConstClass.BUFFERSIZE)) { buffersize = htServer[XMLConstClass.BUFFERSIZE].ToString(); } IServerConfig nannyclient_serverconfig = new SocketServer.ServerConfig() { Port = Convert.ToInt16(port), MaxClientCount = Convert.ToInt16(maxclient), RecOutTime = Convert.ToInt16(rcvtimeout), ReceiveBufferSize = Convert.ToInt16(buffersize), SendBufferSize = Convert.ToInt16(buffersize) }; if (_server == null) { _server = new TCPServer(); _server.ReceiveMes += _server_ReceiveMes; } if (!_server.Setup(nannyclient_serverconfig)) { return(false); } else { if (!_server.Start()) { return(false); } } return(true); } catch (Exception ex) { DelegateState.InvokeDispatchStateEvent(ex.Message); return(false); } }
public void Start() { Task.Run(() => { try { //while (true) //{ // OperateResult opr = melsecMc.ConnectServer(); // if (!opr.IsSuccess) // { // DelegateState.InvokeDispatchStateEvent("呼叫器:" + this.PLCCode.ToString() + "IP:" + melsecMc.IpAddress + "连接失败! 将重新尝试连接..."); // Thread.Sleep(60 * 1000); // //return false; // } // else // { // break; // } //} melsecMc.SetPersistentConnection(); DelegateState.InvokeDispatchStateEvent("呼叫器:" + this.PLCCode.ToString() + "IP:" + melsecMc.IpAddress + "连接成功!"); processor = new Thread(Polling); processor.IsBackground = true; processor.Start(); } catch (Exception ex) { DelegateState.InvokeDispatchStateEvent(ex.Message); } }); }
public bool InitSiemens() { try { melsecMc = new SiemensS7Net(SiemensPLCS.S1200) { IpAddress = this.ConnParam.ServerIP, Port = this.ConnParam.Port }; return(true); } catch (Exception ex) { DelegateState.InvokeDispatchStateEvent(ex.Message); return(false); } }
/// <summary> /// 重新创建连接 /// </summary> public void ReConnect() { try { //LastConnectTime = DateTime.Now; if (Init()) { CarBaseStateInfo car = new CarBaseStateInfo(); car.AgvID = this.DeviceID; LastConnectTime = DateTime.Now; ReStart(); } } catch (Exception ex) { DelegateState.InvokeDispatchStateEvent("尝试连接" + this.DeviceID.ToString() + "车异常,将在3秒后重新尝试连接..."); } }
/// <summary> /// 添加IO设备指令 /// </summary> public void IO_AddControl(int ioid, CommandToValue ctov) { try { IOSession_Fbell session = IOSessions.FirstOrDefault(p => p.DeviceID == ioid); if (session != null) { session.QueueCommand.Enqueue(ctov); } else { DelegateState.InvokeDispatchStateEvent("添加指令失败,未能找到" + ioid.ToString() + "号IO设备 "); } } catch (Exception ex) { DelegateState.InvokeDispatchStateEvent("添加IO设备指令异常"); } }
/// <summary> /// 添加充电桩指令 /// </summary> /// <param name="chargeid"></param> /// <param name="ctov"></param> public void Charge_AddControl(int chargeid, CommandToValue ctov) { try { AGVSessionBase session = ChargeStationSessions.FirstOrDefault(p => (p as AGVSessionBase).DeviceID == chargeid) as AGVSessionBase; if (session != null) { session.QueueCommand.Enqueue(ctov); } else { DelegateState.InvokeDispatchStateEvent("添加指令失败,未能找到" + chargeid.ToString() + "号充电桩 "); } } catch (Exception ex) { DelegateState.InvokeDispatchStateEvent("添加充电桩指令异常"); } }
private bool HandleCallBoxMonitor(CallBoxInfo CallBox, CallBoxDetail CurrBoxDetail, int staragestate, string codes = "") { try { lock (lockstorage) { #region 处理监控功能 //处理监控功能 //监控功能则为更新储位的状态 DataTable dtstorage = CoreData.dbOperator.LoadDatas("QueryAllStore"); CoreData.StorageList = DataToObject.TableToEntity <StorageInfo>(dtstorage); StorageInfo CallStore = CoreData.StorageList.FirstOrDefault(q => q.ID == CurrBoxDetail.LocationID); if (CallStore == null) { LogHelper.WriteCallBoxLog("未配置按钮盒" + CallBox.CallBoxID.ToString() + "对应的监控储位"); return(false); } int StoreState = staragestate; if (CallStore.StorageState != StoreState) { //更新数据库中的对应监控的储位状态信息 AGVServerDAccess.UpdateStorageState(StoreState, -1, CallStore.ID); if (!string.IsNullOrEmpty(codes)) { //更新备注 AGVServerDAccess.UpdteStorageRemark(CallStore.ID, codes); } //更新储位的名称 逗号分隔 CallStore.StorageState = StoreState; CallStore.Remark = codes; } return(true); #endregion } } catch (Exception ex) { DelegateState.InvokeDispatchStateEvent(ex.Message); return(false); } }
/// <summary> /// 添加AGV发送指令 /// </summary> public void AGV_AddControl(int AGVID, CommandToValue ctov) { try { AGVSessionBase session = AGVSessions.FirstOrDefault(p => (p as AGVSessionBase).DeviceID == AGVID) as AGVSessionBase; if (session != null) { //LogHelper.WriteCreatTaskLog("添加AGV:"+ AGVID.ToString()+"指令-->"+ ctov.Command.ToString()); session.QueueCommand.Enqueue(ctov); } else { DelegateState.InvokeDispatchStateEvent("添加指令失败,未能找到" + AGVID.ToString() + "号AGV通信管道!"); LogHelper.WriteLog("添加指令失败,未能找到" + AGVID.ToString() + "号AGV通信管道!"); } } catch (Exception ex) { DelegateState.InvokeDispatchStateEvent("添加指令异常"); LogHelper.WriteErrorLog(ex); } }
/// <summary> /// 重新创建连接 /// </summary> public void ReConnect() { try { LastConnectTime = DateTime.Now; if (Init()) { IODeviceInfo IOInfo = new IODeviceInfo(); IOInfo.ID = this.DeviceID; if (ReStart()) { LastConnectTime = DateTime.Now; } else { DelegateState.InvokeDispatchStateEvent("尝试连接" + this.DeviceID.ToString() + "号IO设备..."); IOInfo.bIsCommBreak = true; DelegateState.InvokeIOFeedBackEvent(IOInfo); } } else { DelegateState.InvokeDispatchStateEvent("尝试连接" + this.DeviceID.ToString() + "号IO设备..."); IODeviceInfo IOInfo = new IODeviceInfo(); IOInfo.ID = DeviceID; IOInfo.bIsCommBreak = true; DelegateState.InvokeIOFeedBackEvent(IOInfo); } } catch (Exception ex) { DelegateState.InvokeDispatchStateEvent("尝试连接" + this.DeviceID.ToString() + "号IO设备..."); IODeviceInfo IOInfo = new IODeviceInfo(); IOInfo.ID = DeviceID; IOInfo.bIsCommBreak = true; DelegateState.InvokeIOFeedBackEvent(IOInfo); } }
private bool Stop() { try { foreach (CommunicationSiemensPlc commer in Seccions) { if (!commer.Stop()) { DelegateState.InvokeDispatchStateEvent("呼叫器:" + commer.PLCCode.ToString() + "IP:" + commer.ConnParam.ServerIP + "停止失败!"); } else { DelegateState.InvokeDispatchStateEvent("呼叫器:" + commer.PLCCode.ToString() + "IP:" + commer.ConnParam.ServerIP + "停止成功!"); } } return(true); } catch (Exception ex) { DelegateState.InvokeDispatchStateEvent(ex.Message); return(false); } }
public bool Stop() { try { melsecMc.ConnectClose(); melsecMc.Dispose(); if (processor != null) { processor.Abort(); //解决线程过多情况,因为线程执行Abort,状态是AbortRequested,还是会存在继续执行 while (processor.ThreadState != ThreadState.Aborted) { Thread.Sleep(100); } } return(true); } catch (Exception ex) { DelegateState.InvokeDispatchStateEvent(ex.Message); return(false); } }
private bool InitAndStartServer() { try { DelegateState.InvokeDispatchStateEvent("正在读取数据库连接..."); ConnectConfigTool.setDBase(); if (ConnectConfigTool.DBase == null) { DelegateState.InvokeDispatchStateEvent("数据库连接文件不存在!"); return(false); } IDbOperator dbOperator = CreateDbOperator.DbOperatorInstance(ConnectConfigTool.DBase); if (dbOperator == null) { DelegateState.InvokeDispatchStateEvent("数据库连接文件不存在!"); return(false); } bool IsConnectDB = false; try { IsConnectDB = dbOperator.ServerIsThrough(); } catch (Exception ex) { DelegateState.InvokeDispatchStateEvent("数据库连接失败【" + ex.Message + "】"); } if (!IsConnectDB) { return(false); } CoreData.dbOperator = dbOperator; #region 读取系统参数 DelegateState.InvokeDispatchStateEvent("正在读取系统参数..."); DataTable dtSysparameter = CoreData.dbOperator.LoadDatas("QuerySyspara"); foreach (DataRow row in dtSysparameter.Rows) { CoreData.SysParameter[row["ParameterCode"].ToString()] = row["ParameterValue"].ToString(); } DelegateState.InvokeDispatchStateEvent("读取系统参数成功..."); #endregion DataTable dtAllCallBox = CoreData.dbOperator.LoadDatas("QueryAllCallBox"); CoreData.AllCallBoxes = DataToObject.TableToEntity <CallBoxInfo>(dtAllCallBox); DataTable dtAllCallBoxDetail = CoreData.dbOperator.LoadDatas("QueryAllCallBoxDetails"); CoreData.AllCallBoxDetail = DataToObject.TableToEntity <CallBoxDetail>(dtAllCallBoxDetail); //读取储位 DataTable dtstorage = CoreData.dbOperator.LoadDatas("QueryAllStore"); CoreData.StorageList = DataToObject.TableToEntity <StorageInfo>(dtstorage); //读取区域 DataTable dtarea = CoreData.dbOperator.LoadDatas("LoadAllArea"); CoreData.AllAreaList = DataToObject.TableToEntity <AreaInfo>(dtarea); //初始化呼叫器通信 Seccions.Clear(); foreach (CallBoxInfo callbox in CoreData.AllCallBoxes) { //if (callbox.CallBoxID != 5) //{ // continue; //} SiemensConnectInfo ConnConfig = new SiemensConnectInfo() { ServerIP = callbox.CallBoxIP, Port = callbox.CallBoxPort }; CommunicationSiemensPlc Commer = new CommunicationSiemensPlc(callbox.CallBoxID, ConnConfig); if (!Commer.InitSiemens()) { DelegateState.InvokeDispatchStateEvent("初始化呼叫器:" + callbox.CallBoxID.ToString() + "IP:" + "callbox.CallBoxIP" + "失败!"); continue; } Commer.Start(); Seccions.Add(Commer); } DelegateState.InvokeDispatchStateEvent("初始化成功..."); return(true); } catch (Exception ex) { DelegateState.InvokeDispatchStateEvent(ex.Message); return(false); } }
/// <summary> /// 启动通讯 /// </summary> public bool Start() { try { foreach (var item in AGVSessions) { new Thread(delegate() { bool StartResult = (bool)ExcuteRflectMethod(item, "Start", null); if (StartResult) { DelegateState.InvokeDispatchStateEvent(GetModelValue("DeviceID", item).ToString() + "号AGV启动通讯成功"); LogHelper.WriteLog(GetModelValue("DeviceID", item).ToString() + "号AGV启动通讯成功"); } else { try { CarInfo Car = CoreData.CarList.FirstOrDefault(p => p.AgvID == Convert.ToInt16(GetModelValue("DeviceID", item))); if (Car != null) { Car.bIsCommBreak = true; } } catch { } DelegateState.InvokeDispatchStateEvent(GetModelValue("DeviceID", item).ToString() + "号AGV启动通讯失败"); LogHelper.WriteLog(GetModelValue("DeviceID", item).ToString() + "号AGV启动通讯失败"); } }) { IsBackground = true }.Start(); } foreach (var item in ChargeStationSessions) { new Thread(delegate() { bool StartResult = (bool)ExcuteRflectMethod(item, "Start", null); if (StartResult) { DelegateState.InvokeDispatchStateEvent(GetModelValue("DeviceID", item).ToString() + "号充电桩通讯启动成功..."); } else { DelegateState.InvokeDispatchStateEvent(GetModelValue("DeviceID", item).ToString() + "号充电桩通讯启动失败..."); } }) { IsBackground = true }.Start(); } foreach (var item in IOSessions) { new Thread(delegate() { if (item.Start()) { DelegateState.InvokeDispatchStateEvent(item.DeviceID.ToString() + "号IO设备通讯启动成功..."); } else { IODeviceInfo IOInfo = CoreData.IOList.FirstOrDefault(p => p.ID == item.DeviceID); if (IOInfo != null) { IOInfo.bIsCommBreak = true; } DelegateState.InvokeDispatchStateEvent(item.DeviceID.ToString() + "号IO设备通讯启动失败..."); } }) { IsBackground = true }.Start(); } return(true); } catch (Exception ex) { DelegateState.InvokeDispatchStateEvent("设备通讯启动异常"); LogHelper.WriteErrorLog(ex); return(false); } }
/// <summary> /// 处理呼叫器呼叫任务 /// </summary> /// <param name="CallBox"></param> /// <param name="CurrBoxDetail"></param> /// <param name="BtnID"></param> /// <returns></returns> private bool HandleCallBoxCall(CallBoxInfo CallBox, CallBoxDetail CurrBoxDetail, int BtnID) { try { lock (lockstorage) { #region 处理呼叫逻辑 //加载是否启用储位状态 string IsUserStoreState = CoreData.SysParameter["IsUserStoreState"].ToString(); if (string.IsNullOrEmpty(IsUserStoreState)) { IsUserStoreState = "否"; } int CallBoxID = CallBox.CallBoxID; IList <TaskConfigDetail> TaskConfigDetails = AGVClientDAccess.load_TaskDetail(CurrBoxDetail.TaskConditonCode); if (TaskConfigDetails == null && (TaskConfigDetails != null && TaskConfigDetails.Count <= 0)) { LogHelper.WriteCallBoxLog("未配置按钮盒" + CallBox.CallBoxID.ToString() + "任务信息"); return(false); } DataTable dtstorage = CoreData.dbOperator.LoadDatas("QueryAllStore"); CoreData.StorageList = DataToObject.TableToEntity <StorageInfo>(dtstorage); //开始根据任务配置信息创建任务 StorageInfo CallStore = CoreData.StorageList.FirstOrDefault(q => q.ID == CurrBoxDetail.LocationID); if (CallStore == null) { LogHelper.WriteCallBoxLog("未配置按钮盒" + CallBox.CallBoxID.ToString() + "对应的监控储位"); return(false); } //验证当前按钮盒下是否存在未完成的任务 if (AGVSimulationDAccess.ChekAllowCreatTask(CallBoxID, CallStore.LankMarkCode, CurrBoxDetail.ButtonID) > 0) { LogHelper.WriteCallBoxLog("按钮盒" + CallBox.CallBoxID.ToString() + "对应呼叫存在未完成任务,请稍后再试!"); return(false); } //验证当前按钮盒下是否存在未完成的任务 if (AGVSimulationDAccess.ChekAllowCreatTask2(CallBoxID, CallStore.LankMarkCode, CurrBoxDetail.ButtonID) > 0) { LogHelper.WriteCallBoxLog("按钮盒" + CallBox.CallBoxID.ToString() + "对应呼叫存在未完成任务 未回写的任务,请稍后再试!"); return(false); } AreaInfo callarea = CoreData.AllAreaList.FirstOrDefault(p => p.OwnArea == CallStore.OwnArea); if (callarea != null && callarea.MaxTaskCount > 0) { if (AGVSimulationDAccess.ChekAllowCreatTask3(callarea.OwnArea) >= callarea.MaxTaskCount) { LogHelper.WriteCallBoxLog("按钮盒" + CallBox.CallBoxIP.ToString() + " 地址" + CurrBoxDetail.DBAddress + " 对应的区域任务数量达到最大,不产生任务"); return(false); } } if (!string.IsNullOrEmpty(CallStore.StorageName)) { LogHelper.WriteCallBoxLog("按钮盒" + CallBox.CallBoxIP.ToString() + " 地址" + CurrBoxDetail.DBAddress + "对应储位未启用"); return(false); } //组装任务信息 string dispatchNo = Guid.NewGuid().ToString(); DispatchTaskInfo TaskInfo = new DispatchTaskInfo(); TaskInfo.dispatchNo = dispatchNo; TaskInfo.TaskState = 0; TaskInfo.CallLand = CallStore.LankMarkCode; TaskInfo.stationNo = CallBoxID; TaskInfo.CallID = BtnID; TaskInfo.taskType = 0; TaskInfo.OwerArea = CallStore.OwnArea; //创建任务明细 int DetailID = 1; int PrePutType = -1; foreach (TaskConfigDetail item in TaskConfigDetails) { //通过任务任务配置明细寻找目标地标 StorageInfo ArmStore = null; LogHelper.WriteCallBoxLog("呼叫储位为:" + item.ArmOwnArea.ToString()); if (item.ArmOwnArea == -1) { ArmStore = CallStore; LogHelper.WriteCallBoxLog("呼叫储位地标为:" + CallStore.LankMarkCode); } else { if (IsUserStoreState == "否") { ArmStore = CoreData.StorageList.FirstOrDefault(p => p.OwnArea == item.ArmOwnArea && p.StorageState == item.StorageState && p.MaterielType == item.MaterialType); } else { ArmStore = CoreData.StorageList.FirstOrDefault(p => p.OwnArea == item.ArmOwnArea && p.StorageState == item.StorageState && p.MaterielType == item.MaterialType && p.LockState == 0); } } if (ArmStore == null) { LogHelper.WriteCallBoxLog(string.Format("按钮盒{0} 地址:{1} BtnID{2} 对应呼叫,目的储位不存在[原因:不存在或被占用]", CallBox.CallBoxID, CurrBoxDetail.DBAddress, CurrBoxDetail.ButtonID)); return(false); } #region 用 //再通过配置任务号来处理必经地标 IList <TaskConfigMustPass> ConfigMustPasses = AGVServerDAccess.LoadTaskMustPass(item.TaskConditonCode, item.DetailID); if (ConfigMustPasses != null && ConfigMustPasses.Count > 0) { ////如果配置的必经地标则需要产生任务经过必经地标 foreach (TaskConfigMustPass MustPassItem in ConfigMustPasses) { foreach (IOActionInfo Action in MustPassItem.MustPassIOAction) { IOActionInfo CurrIOActionInfo = AGVServerDAccess.LoadAllIOAction(Action.ActionID); if (CurrIOActionInfo == null) { LogHelper.WriteCallBoxLog("按钮器" + CallBox.CallBoxID.ToString() + "对应呼叫,必经地标中的IO动作" + Action.ActionID.ToString() + "档案信息不存在"); continue; } DispatchTaskDetail newTaskDetail = new DispatchTaskDetail(); newTaskDetail.dispatchNo = dispatchNo; newTaskDetail.DetailID = DetailID; newTaskDetail.LandCode = MustPassItem.MustPassLandCode; newTaskDetail.IsAllowExcute = Action.IsPass; newTaskDetail.IsSensorStop = 0; newTaskDetail.OperType = -1; newTaskDetail.IsWait = Action.IsWait; newTaskDetail.WaitTime = Action.WaitTime; newTaskDetail.TaskConditonCode = MustPassItem.TaskConditonCode; newTaskDetail.TaskConfigDetailID = item.DetailID; TaskInfo.TaskDetail.Add(newTaskDetail); } } } #endregion //如果没有必经地标或者添加完必经地标后需要继续添加后续的任务配置明细 DispatchTaskDetail dispathDetail_TaskConfig = new DispatchTaskDetail(); dispathDetail_TaskConfig.dispatchNo = dispatchNo; dispathDetail_TaskConfig.DetailID = DetailID; dispathDetail_TaskConfig.LandCode = ArmStore.LankMarkCode; dispathDetail_TaskConfig.StorageID = ArmStore.ID; if (!string.IsNullOrEmpty(ArmStore.Remark)) { TaskInfo.GoodsInfo = ArmStore.Remark; } dispathDetail_TaskConfig.OperType = item.Action; dispathDetail_TaskConfig.IsAllowExcute = item.IsWaitPass; dispathDetail_TaskConfig.PassType = item.PassType; dispathDetail_TaskConfig.IsNeedCallBack = item.IsNeedCallBack; dispathDetail_TaskConfig.IsCallGoods = item.IsCallGoods; if (PrePutType == -1) { dispathDetail_TaskConfig.PutType = ArmStore.StorageState; } else { dispathDetail_TaskConfig.PutType = PrePutType; } dispathDetail_TaskConfig.IsSensorStop = item.IsSensorStop; TaskInfo.TaskDetail.Add(dispathDetail_TaskConfig); PrePutType = ArmStore.StorageState; DetailID += 1; }//结束循环处理任务配置 //循环组装完任务信息后保存到数据库 if (TaskInfo != null && TaskInfo.TaskDetail.Count > 0) { AGVServerDAccess.CreatTaskInfo(TaskInfo, IsUserStoreState == "是" ? true : false); } return(true); #endregion } } catch (Exception ex) { DelegateState.InvokeDispatchStateEvent(ex.Message); return(false); } }
/// <summary> /// 给一个客户提供服务,接受公司an【】 /// </summary> /// <param name="obj"></param> public void ServiceClient(object obj) { try { //lock (lockRiceve) //{ bool keepalive = true; AppSession clientsession = FindSession(obj.ToString()); if (clientsession == null) { keepalive = false; return; } DelegateState.InvokeDispatchStateEvent(clientsession._clientsocket.RemoteEndPoint.ToString() + "已连接"); try { while (keepalive) { //处理接受包 int offlinecount = 0; int allheadleftlengh = 6; int receivedlengh = 0; byte[] bufferhead = new byte[6]; while (allheadleftlengh - receivedlengh > 0) { byte[] buffertemp = new byte[allheadleftlengh - receivedlengh]; int lengh = clientsession.ClientSocket.Receive(buffertemp); if (lengh <= 0) { if (offlinecount == 3) { throw new Exception("Socket 错误!"); } offlinecount += 1; Thread.Sleep(1000 * 2); } Buffer.BlockCopy(buffertemp, 0, bufferhead, receivedlengh, lengh); receivedlengh += lengh; clientsession._lastactivedatetime = DateTime.Now; } offlinecount = 0; receivedlengh = 0; int allcontentleftlengh = int.Parse(Convert.ToString(bufferhead[5], 10)); //Convert.ToInt32(Convert.ToString(bufferhead[4], 2).PadLeft(8, '0') + Convert.ToString(bufferhead[5], 2).PadLeft(8, '0'), 2); byte[] buffercontent = new byte[allcontentleftlengh]; while (allcontentleftlengh - receivedlengh > 0) { byte[] buffertemp = new byte[allcontentleftlengh - receivedlengh]; int lengh = clientsession.ClientSocket.Receive(buffertemp); if (lengh <= 0) { if (offlinecount == 3) { throw new Exception("Socket 错误!"); } offlinecount += 1; Thread.Sleep(1000 * 2); } Buffer.BlockCopy(buffertemp, 0, buffercontent, receivedlengh, lengh); receivedlengh += lengh; clientsession._lastactivedatetime = DateTime.Now; } //List<byte> msg = buffercontent.ToList(); //记录接受日志 List <byte> msg = new List <byte>(); msg.AddRange(bufferhead); msg.AddRange(buffercontent); string log_text = ""; foreach (byte item in msg) { log_text += ((int)item).ToString("X") + " "; } string IP = ((IPEndPoint)clientsession.ClientSocket.RemoteEndPoint).Address.ToString(); LogHelper.WriteCallBoxLog("接受到IP地址为【" + IP + "】指令:" + log_text); //接受完外部指令后处理回掉处理逻辑 List <byte> CallBoxConten = new List <byte>(); CallBoxConten.AddRange(buffercontent); if (ReceiveMes != null) { ReceiveMes(new NetEventArgs(clientsession, CallBoxConten)); } } } catch (Exception ex) { LogHelper.WriteErrorLog(ex); } //} } catch (Exception ex) { LogHelper.WriteErrorLog(ex); } }
/// <summary> /// 通讯初始化 /// </summary> public bool CommInit() { try { #region 小车 DispatchAssembly AgvCommunitClass = CoreData.DispathAssemblies.FirstOrDefault(p => p.AssemblyType == 0); if (AgvCommunitClass == null) { DelegateState.InvokeDispatchStateEvent("未配置AGV通信处理程序!"); LogHelper.WriteLog("未配置AGV通信处理程序!"); return(false); } DispatchAssembly ChargeCommunitClass = CoreData.DispathAssemblies.FirstOrDefault(q => q.AssemblyType == 1); if (ChargeCommunitClass == null) { DelegateState.InvokeDispatchStateEvent("未配置充电桩通信处理程序!"); LogHelper.WriteLog("未配置充电桩通信处理程序!"); return(false); } //先停止清除所有的通信管道 foreach (var item in AGVSessions) { ExcuteRflectMethod(item, "Stop", null); } AGVSessions.Clear(); //初始化所有AGV小车的通信 foreach (CarInfo car in CoreData.CarList) { AGVComPara para = new AGVComPara(); para.ServerIP = car.CarIP; para.Port = Convert.ToInt32(car.CarPort); int agvid = Convert.ToInt32(car.AgvID); Type objType = Type.GetType(AgvCommunitClass.ClassName, true); object obj = Activator.CreateInstance(objType); SetModelValue("DeviceID", agvid, obj); SetModelValue("ComPara", para, obj); //obj.DeviceID = agvid; //obj.ComPara = para; AGVSessions.Add(obj); } foreach (var item in AGVSessions) { bool InitResult = (bool)ExcuteRflectMethod(item, "Init", null); if (InitResult) { DelegateState.InvokeDispatchStateEvent(GetModelValue("DeviceID", item).ToString() + "号AGV通讯初始化成功"); LogHelper.WriteLog(GetModelValue("DeviceID", item).ToString() + "号AGV通讯初始化成功"); } else { DelegateState.InvokeDispatchStateEvent(GetModelValue("DeviceID", item).ToString() + "号AGV通讯初始化失败"); LogHelper.WriteLog(GetModelValue("DeviceID", item).ToString() + "号AGV通讯初始化失败"); } } #endregion #region 充电桩 foreach (var item in ChargeStationSessions) { ExcuteRflectMethod(item, "Stop", null); } ChargeStationSessions.Clear(); foreach (ChargeStationInfo Charge in CoreData.ChargeList) { AGVComPara para = new AGVComPara(); para.ServerIP = Charge.IP; para.Port = Convert.ToInt32(Charge.Port); int ChargeID = Convert.ToInt32(Charge.ID); Type objType = Type.GetType(ChargeCommunitClass.ClassName, true); object obj = Activator.CreateInstance(objType); SetModelValue("DeviceID", ChargeID, obj); SetModelValue("ComPara", para, obj); ChargeStationSessions.Add(obj); } foreach (var item in ChargeStationSessions) { bool InitResult = (bool)ExcuteRflectMethod(item, "Init", null); if (InitResult) { DelegateState.InvokeDispatchStateEvent(GetModelValue("DeviceID", item).ToString() + "号充电桩通讯初始化成功"); } else { DelegateState.InvokeDispatchStateEvent(GetModelValue("DeviceID", item).ToString() + "号充电桩通讯初始化失败"); } } #endregion #region io设备 foreach (var item in IOSessions) { item.Stop(); } IOSessions.Clear(); foreach (IODeviceInfo node in CoreData.IOList) { AGVComPara para = new AGVComPara(); para.ServerIP = node.IP; para.Port = Convert.ToInt32(node.Port); int ioid = Convert.ToInt32(node.ID); IOSessions.Add(new IOSession_Fbell(ioid, para)); } foreach (var item in IOSessions) { if (item.Init()) { DelegateState.InvokeDispatchStateEvent(item.DeviceID.ToString() + "号IO设备通讯初始化成功"); } else { DelegateState.InvokeDispatchStateEvent(item.DeviceID.ToString() + "号IO设备通讯初始化失败"); } } #endregion return(true); } catch (Exception ex) { DelegateState.InvokeDispatchStateEvent("初始化客户端通讯异常"); LogHelper.WriteErrorLog(ex); return(false); } }