/// <summary> /// when Client Try to connect server /// </summary> /// <param name="o"></param> private void Acceptor(IAsyncResult o) { TcpListener server = o.AsyncState as TcpListener; try { OutBufferClient newClient = new OutBufferClient(); newClient.NetWork = server.EndAcceptTcpClient(o); lstClient.Add(newClient); LogerHelper2.ToLog("Robot outBuffer " + newClient.Name + " is connected now.", 0); //RobotoutBuffer Status.UpdateRobotoutBuffer Status("Connected"); //isoutBuffer onLine = true; newClient.NetWork.GetStream().BeginRead(newClient.buffer, 0, newClient.buffer.Length, new AsyncCallback(TCPCallBack), newClient); server.BeginAcceptTcpClient(new AsyncCallback(Acceptor), server);//continue listening //send F999 to active outBuffer QueryMessageListAndRunFirstMessage("DUTSTATUS"); // byte[] tempdata = Encoding.ASCII.GetBytes("F999"); //MessageReceived.BeginInvoke("", MainoutBuffer Message.ConvertByteToMessage(tempdata), null, null);//async data output //Server. QueryMessageListAndRunFirstMessage("DUTSTATUS"); } catch (Exception ex) { LogerHelper2.ToLog("test method outBuffer Servers.Acceptor catch exception" + ex.Message, 3); } }
/// <summary> /// the reset funtion open/close setting /// </summary> /// <param name="isSupportReTest"></param> public void updateReTestRuleSetting(bool isSupportReTest, int alarmAfterDUTFailTimes) { DUTReTest.isSupportReTest = isSupportReTest; DUTReTest.alarmWhenDUTTestFailTimes = alarmAfterDUTFailTimes; LogerHelper2.ToLog(("Re-test Rule Setting to " + isSupportReTest), 2); LogerHelper2.ToLog(("Alarm After DUT Fail Times Setting to " + alarmAfterDUTFailTimes), 2); }
public void ConnectToServer(string ip, int port) { //client.NetWork. try { LogerHelper2.ToLog(string.Format("Connecting to Server: {0}:{1}", ip, port), 3); client = new TCPIPClient(); client.NetWork = new TcpClient(); client.NetWork.Connect(ip.Trim(), port);//connect to server client.SetName(); client.NetWork.GetStream().BeginRead(client.buffer, 0, client.buffer.Length, new AsyncCallback(TCPCallBack), client); IsConnected = true; //if (client.NetWork.Connected) //{ // ServerConnected(client, true); //} // lstClient.Add(client); // BindLstClient(); TxCount = 0; } catch (Exception ex) { IsConnected = false; client.Disconnect(); //ServerConnected(client, false); MessageBox.Show("不能连接到库房App,请检查库房App是否打开.", "程序启动"); LogerHelper2.ToLog("connecting Exception:" + ex.Message, 3); } }
/// <summary> /// send message to client /// </summary> /// <param name="sender"></param> /// <param name="message"></param> public void SendMessage(string message) { if (isPLConLine == false) { LogerHelper2.ToLog("Robot PLC is offline, can't control or send commond to plc", 3); return; } if (message.Contains("M")) // move command set timer { plcCommandFeedBackTimer.Enabled = true; //timer可用 plcResendCommandTimer.Enabled = true; lastAction = message; // plcCommandFeedBackTimer.Start(); } bool b = true; string s = string.Format("to PLC: {0}", message); LogerHelper2.ToLog(s, 1); byte[] byteMessage = Encoding.ASCII.GetBytes(message); // lstClient[lstClient.Count - 1].NetWork.GetStream().Write(byteMessage, 0, byteMessage.Length); //for (int i = 0; i < 3; i++) // if first time is send fail, then send again //{ b = Send(byteMessage, lstClient[lstClient.Count - 1]); // if (b == false) // { // continue; // } // else // break; //} }
/// <summary> /// init client connect /// </summary> /// <param name="o"></param> private void Acceptor(IAsyncResult o) { TcpListener server = o.AsyncState as TcpListener; try { TCPIPClient newClient = new TCPIPClient(); newClient.NetWork = server.EndAcceptTcpClient(o); if (lstClient.Count > 0) //Server need to update the listClient(not to add new) when the connection was created from the same Client { int endIndex = newClient.Name.IndexOf(":"); string s = newClient.Name.Substring(0, endIndex - 1); for (int i = 0; i < lstClient.Count; i++) { if (lstClient[i].Name.Contains(s) && lstClient[i].Name != newClient.Name) { LogerHelper2.ToLog("old client : " + lstClient[i].Name + " has been killed!", 2); lstClient[i].Disconnect(); lstClient.Remove(lstClient[i]); } } } lstClient.Add(newClient); newClient.isClientOnline = true; LogerHelper2.ToLog("client : " + newClient.Name + " is connect to server", 2); newClient.NetWork.GetStream().BeginRead(newClient.buffer, 0, newClient.buffer.Length, new AsyncCallback(TCPCallBack), newClient); server.BeginAcceptTcpClient(new AsyncCallback(Acceptor), server);//continue moniter client } catch (ObjectDisposedException ex) { LogerHelper2.ToLog(ex.Message, 3); } }
/// <summary> /// the event of server receive message from station client, different messagetype do different action /// </summary> /// <param name="sender">station client ip&port</param> /// <param name="msg">station client message</param> public void server_MessageReceived(object sender, Message msg) { if (msg.InvalidMessage == true) { LogerHelper2.ToLog("error format commond" + msg.Info, 3); return; } string msgTemp = string.Format("From: {1} Info:{0}", msg.totalmessage, sender.ToString()); CommonMethod.RegisterIPtoStation(msg.stationId, sender.ToString()); switch (msg.MsgType) { case MsgType.Status: AH_Status(msg); break; case MsgType.Register: AH_Register(msg, "r"); break; default: break; } }
/// <summary> /// when server haven't receive the guf feedback in time, then do this action /// </summary> /// <param name="source"></param> /// <param name="e"></param> public void OnTimedShow(object source, ElapsedEventArgs e) { isGufFeedBack = false; LogerHelper2.ToLog("Server doesn't receive the guf feedback in time", 3); Server.stationList[stationId - 1].errorInfo = "Server doesn't receive the guf feedback in time"; ClientGUFStatus.UpdateStationsData(stationId, 4, ClientStatusType.Error); }
/// <summary> /// when server haven't receive the client in time, then do this action /// </summary> /// <param name="source"></param> /// <param name="e"></param> public void OnTimedShow(object source, ElapsedEventArgs e) { hertbeatCount = 0; LogerHelper2.ToLog("Server doesn't receive the Client Heartbeat in time from station" + stationId.ToString(), 3); Server.stationList[stationId - 1].errorInfo = "Server doesn't receive the Client Heartbeat in time"; ClientGUFStatus.UpdateStationsData(stationId, 1, ClientStatusType.Error); ClientGUFStatus.UpdateStationsData(stationId, 4, ClientStatusType.Error); }
/// <summary> /// while the server didn't receive the ACK for move command from plc, then resend CMD /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void plcResendTimer_Elapsed(object sender, ElapsedEventArgs e) { LogerHelper2.ToLog("Server does not receive the PLC command ACK in time", 3); if (lastAction != string.Empty) { SendMessage(lastAction); } }
/// <summary> /// callback method /// </summary> /// <param name="ar"></param> private void TCPCallBack(IAsyncResult ar) { TCPIPClient client = (TCPIPClient)ar.AsyncState; if (client.NetWork.Connected) { try { NetworkStream ns = client.NetWork.GetStream(); byte[] recdata = new byte[ns.EndRead(ar)]; string receivedstring = (new ASCIIEncoding().GetString(client.buffer)); receivedstring = receivedstring.Substring(0, recdata.Length); if (recdata.Length > 0) { if (receivedstring.Contains("\r\n")) { string[] recdataArray = receivedstring.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < recdataArray.Length; i++) { if (MessageReceived != null) { MessageReceived.BeginInvoke(client.Name, Message.ConvertStringToMessage(recdataArray[i]), null, null);//async output data } } ns.BeginRead(client.buffer, 0, client.buffer.Length, new AsyncCallback(TCPCallBack), client); } else { Array.Copy(client.buffer, recdata, recdata.Length); if (MessageReceived != null) { MessageReceived.BeginInvoke(client.Name, Message.ConvertByteToMessage(recdata), null, null);//async output data } ns.BeginRead(client.buffer, 0, client.buffer.Length, new AsyncCallback(TCPCallBack), client); } } else { client.Disconnect(); LogerHelper2.ToLog("client :" + client.Name + " is disconnect from server", 2); client.isClientOnline = false; CommonMethod.ShowClientOffLine(client.Name); lstClient.Remove(client); } } catch (Exception ex) { client.Disconnect(); LogerHelper2.ToLog(ex.Message + "client :" + client.Name + " is disconnect from server", 3); client.isClientOnline = false; CommonMethod.ShowClientOffLine(client.Name); lstClient.Remove(client); } } }
/// <summary> /// outBuffer Client send message to server /// </summary> /// <param name="ar"></param> private void TCPCallBack(IAsyncResult ar) { OutBufferClient client = (OutBufferClient)ar.AsyncState; try { if (client.NetWork.Connected) { NetworkStream ns = client.NetWork.GetStream(); byte[] recdata = new byte[ns.EndRead(ar)]; if (recdata.Length > 0) { Array.Copy(client.buffer, recdata, recdata.Length); if (recdata.Length == 1) { if (recdata[0] == 0x01) { _outBuffIsFree = true; } else { _outBuffIsFree = false; } if (_outBuffIsFree != OutBuffIsFree) { OutBuffIsFree = _outBuffIsFree; if (OutBuffChanged != null) { OutBuffChanged.BeginInvoke(client.Name, (_outBuffIsFree), null, null);//async data output } } } client.NetWork.GetStream().Write(_sendData, 0, _sendData.Length); ns.BeginRead(client.buffer, 0, client.buffer.Length, new AsyncCallback(TCPCallBack), client); } else { client.DisConnect(); LogerHelper2.ToLog("outBuffer is disconnected now", 2); //outBuffer HeartBeatTimer.Stop(); //RobotoutBuffer Status.UpdateRobotoutBuffer Status("Disconnected"); //isoutBuffer onLine = false; lstClient.Remove(client); } } } catch (Exception ex) { LogerHelper2.ToLog("testmothod TCPCallBack catch exception " + ex.Message, 3); //RobotoutBuffer Status.UpdateRobotoutBuffer Status("Disconnected"); //outBuffer HeartBeatTimer.Stop(); client.DisConnect(); //isoutBuffer onLine = false; lstClient.Remove(client); } }
/// <summary> /// reset robot PLC status, change the busy to no busy status, so that auto test could restart to work /// </summary> /// <param></param> public void resetRobotPLCState() { PlCisbusy = false; if (dutIdListInQueue.Count > 0) { dutIdListInQueue.RemoveAt(0); } RobotPLCStatus.UpdateRobotPLCStatus("Idle"); LogerHelper2.ToLog("Robot Arm has reset.", 2); }
public void DisconnectFromServer() { if (client.NetWork.Connected) { LogerHelper2.ToLog("Disconnecting from Server", 3); client.Disconnect(); //ServerConnected(client, false); IsConnected = false; } }
/// <summary> /// the message is about register for station client /// </summary> /// <param name="msg"></param> /// <param name="pos"></param> public void AH_Register(Message msg, string pos) { if (pos == "r") { stationList[int.Parse(msg.stationId) - 1].stationNo = int.Parse(msg.Info); stationList[int.Parse(msg.stationId) - 1].isAvaliable = true; stationList[int.Parse(msg.stationId) - 1].errorInfo = ""; // after stationList[int.Parse(msg.stationId) - 1].aTimer.Enabled = true; //timer可用 //UpdateStation(msg.stationId, ClientStatusType.Idle); LogerHelper2.ToAutoTestLogFile(DateTime.Now.ToString() + ": Tester " + msg.stationId + " register to server"); } else if (pos == "g") { gufList[int.Parse(msg.stationId) - 1].stationNo = int.Parse(msg.Info); if (gufList[int.Parse(msg.stationId) - 1].stationId == -1) { // first time to register GUF gufList[int.Parse(msg.stationId) - 1].gufStatus = 0; //0-OK gufList[int.Parse(msg.stationId) - 1].stationId = int.Parse(msg.stationId); UpdateStation(msg.stationId, ClientStatusType.Idle); } else { //recover the GUF int stid = int.Parse(msg.stationId); // if (gufList[stid - 1].gufStatus == 1 && (stationList[stid - 1].errorInfo.ToLower().Contains("heartbeat") && stationList[stid - 1].errorInfo.ToLower().Contains("guf"))) // exception { gufList[int.Parse(msg.stationId) - 1].gufStatus = 0; //0-OK stationList[stid - 1].errorInfo = ""; ClientGUFStatus.UpdateStationsData(stid, 3, ClientStatusType.Pass); ClientGUFStatus.UpdateStationsData(stid, 4, ClientStatusType.Unknown); if (stationList[stid - 1].clientStatusType == ClientStatusType.Idle && stationList[stid - 1].isAvaliable == true) { QueryMessageListAndRunFirstMessage("DUTID"); } } } LogerHelper2.ToAutoTestLogFile(DateTime.Now.ToString() + ": GUF " + msg.stationId + " register to server"); } else if (pos == "x") { gufList[int.Parse(msg.stationId) - 1].stationNo = int.Parse(msg.Info); gufList[int.Parse(msg.stationId) - 1].gufStatus = 0; //0-OK gufList[int.Parse(msg.stationId) - 1].stationId = int.Parse(msg.stationId); stationList[int.Parse(msg.stationId) - 1].errorInfo = ""; // after stationList[int.Parse(msg.stationId) - 1].stationNo = int.Parse(msg.Info); stationList[int.Parse(msg.stationId) - 1].isAvaliable = true; stationList[int.Parse(msg.stationId) - 1].aTimer.Enabled = true; //timer可用 UpdateStation(msg.stationId, ClientStatusType.Idle); LogerHelper2.ToAutoTestLogFile(DateTime.Now.ToString() + ": Tester & GUF " + msg.stationId + " register to server"); } //server.SendMsg(new Message(msg.stationId, msg.MsgId, MsgType.Ack, "ack ok"), stationList[int.Parse(msg.stationId) - 1].ahaddress); }
/// <summary> /// stop listen /// </summary> /// <returns></returns> public void StopServerforoutBuffer() { try { BufferServer.Stop(); //isListen = false; } catch (Exception stopListen_E) { LogerHelper2.ToLog("testmethod StopServerforoutBuffer is catch exception" + stopListen_E.Message, 3); } }
/// <summary> /// stop listen /// </summary> /// <returns></returns> public void StopServerforPLC() { try { plcSever.Stop(); isListen = false; } catch (Exception stopListen_E) { LogerHelper2.ToLog("testmethod StopServerforPLC is catch exception" + stopListen_E.Message, 3); } }
/// <summary> /// stop TCP moniter /// </summary> /// <returns></returns> public void StopTCPServer() { try { tcpsever.Stop(); isListen = false; } catch (Exception stopListen_E) { LogerHelper2.ToLog("methond StopTCPServer catch error :" + stopListen_E.Message, 3); } }
/// <summary> /// clear /// </summary> public void ClearSelf() { foreach (TCPIPClient client in lstClient) { client.Disconnect(); LogerHelper2.ToLog("client :" + client.Name + "is disconnect from server", 2); } lstClient.Clear(); if (tcpsever != null) { tcpsever.Stop(); } }
private bool Send(byte[] data) { try { client.NetWork.GetStream().Write(data, 0, data.Length); TxCount++; } catch (Exception ex) { LogerHelper2.ToLog("Sending Exception:" + ex.Message, 3); return(false); } return(true); }
/// <summary> /// open TCP moniter /// </summary> /// <returns></returns> public void StartTCPServer(string ip, int port) { try { tcpsever = new TcpListener(IPAddress.Parse(ip), port); tcpsever.Start(); tcpsever.BeginAcceptTcpClient(new AsyncCallback(Acceptor), tcpsever); isListen = true; } catch (Exception e) { LogerHelper2.ToLog("methond StartTCPServer catch error :" + e.Message, 3); } }
public void InitClient(string serverIp, int serverPort) { //int port = 8090; //int plcport = 2219; LogerHelper2.ToLog("================== start to connect Server ==================", 2); ctn = new Network.Connection(); //ctn.ServerConnected += ctn_ServerConnected; exit += ctn.DisconnectFromServer; ctn.ConnectToServer(serverIp, serverPort); }
private bool Send(byte[] data, TCPIPClient client) { try { client.NetWork.GetStream().Write(data, 0, data.Length); } catch (Exception ex) { LogerHelper2.ToLog("methond TcpServer.Send catch exception :" + client.Name + ex.Message, 3); client.Disconnect(); return(false); } return(true); }
void SendMsgToServer_ManuallyRestest(int stationNo, string dutid) { //if (PlCisbusy == false) { gufList[stationNo - 1].gufStatus = 0; ClientGUFStatus.UpdateStationsData(stationNo, 3, ClientStatusType.Pass); //PlcMessageQueue.DeleteMsg(stationNo.ToString()); server.SendMsg(new Message(stationNo.ToString(), 1, MsgType.NewDut, dutid), stationList[stationNo - 1].ahaddress);//dutid LogerHelper2.ToLog("Manually Retest DUT " + dutid + " on T" + stationNo, 2); } //else //{ // RobotPLCStatus.UpdateRobotPLCStatus("busy"); //} }
///function to kill socket session /// <summary> /// clear /// </summary> public void ClearSelf() { foreach (OutBufferClient client in lstClient) { //StopServerforoutBuffer(); client.DisConnect(); LogerHelper2.ToLog("outbuffer is disconnected now\r\n", 0); } lstClient.Clear(); if (BufferServer != null) { BufferServer.Stop(); } }
///function to kill socket session /// <summary> /// clear /// </summary> public void ClearSelf() { foreach (PLCClient client in lstClient) { plcHeartBeatTimer.Stop(); StopServerforPLC(); client.DisConnect(); LogerHelper2.ToLog("plc is disconnected now\r\n", 0); } lstClient.Clear(); if (plcSever != null) { plcSever.Stop(); } }
/// <summary> /// disconnect client /// </summary> public void Disconnect() { try { if (_NetWork != null && _NetWork.Connected) { NetworkStream ns = _NetWork.GetStream(); ns.Close(); _NetWork.Close(); } } catch (Exception ex) { LogerHelper2.ToLog("methond Disconnect catch exception" + ex.Message, 3); } }
public void SendMessageToWS(string _prodlineNo, string _messge, MsgType _msgType) { // LogerHelper2.ToLog("================== send message to warehouse ==================", 2); //if (_msgType == MsgType.Register) { //此处 _messge 为 订单号/产品号/订单数量, 用 '|' 分割 ctn.SendMsg(new Network.Message(_prodlineNo, 0, _msgType, _messge.Trim()));//生产前的备料请求 } //else //{ //此处 _messge 为 料号 //ctn.SendMsg(new Network.Message(_prodlineNo, 0, _msgType, _messge)); //生产中的补料和紧急补料请求 //} }
/// <summary> /// server send message to station clinet /// </summary> /// <param name="msg">message information which need to send</param> /// <param name="ip">client ip and port</param> /// <returns></returns> public bool SendMsg(Message msg, string ip) { string s = null; int clientId = 99; bool b = true; for (int i = 0; i < lstClient.Count; i++) { s = lstClient[i].Name; if (string.Compare(ip, s) == 0) { clientId = i; } } if (clientId == 99) { LogerHelper2.ToLog("station:" + msg.stationId + " is offline, can't control or send commond to this station", 3); return(false); } string msgTemp = string.Format("to: {4} StationID: {0}\tMessageID: {1}\tType: {2}\t Info:{3}", msg.stationId, msg.MsgId, msg.MsgType.ToString(), msg.Info, lstClient[clientId].Name); //if (msg.MsgType != MsgType.Ack) //{ // LogerHelper2.ToLog(msgTemp, 1); //} for (int i = 0; i < 3; i++) // if first time is send fail, then send again { b = Send(Message.ConvertMsgToByte(msg), lstClient[clientId]); if (b == false) { LogerHelper2.ToLog("commond send fail", 3); Server.stationList[int.Parse(msg.stationId) - 1].errorInfo = msg.Info + "commond send fail"; ClientGUFStatus.UpdateStationsData(int.Parse(msg.stationId), 4, ClientStatusType.Unknown); continue; } else { break; } } return(b); }
public bool SendMsg(Message msg) { bool success = false; //for (int i = 0; i < 3; i++) { if (success = Send(Message.ConvertMsgToByte(msg))) { //if (msg.MsgType != MsgType.Heartbeat) { LogerHelper2.ToLog(string.Format("Send Msg: {0}", msg.Info), 3); } } else { LogerHelper2.ToLog("Client Send message " + msg.Info.Trim() + " failed...", 3); } } return(success); }
void SendMsgToServer_moveRobotPLCManually(int stationNo, string result) { if (PlCisbusy == false && plcserver.isPLConLine == true) { if (result.Contains("NG")) { plcserver.MoveDUTFromTester(stationNo.ToString(), "01");//fail } else { plcserver.MoveDUTFromTester(stationNo.ToString(), "00");//pass } PlCisbusy = true; LogerHelper2.ToLog("Manually Move DUT from" + stationNo + " to " + result, 2); } else { RobotPLCStatus.UpdateRobotPLCStatus("busy"); } }