/// <summary> /// Receive server message /// </summary> private static void ReceiveWork() { while (!ModuleAbortEvent .WaitOne((int)TimeInterval.VeryVeryShortTime)) { try { // Connect to server ServerSocket.Connect(new IPEndPoint( IPAddress.Parse(ServerIPAddress), ServerPort)); if (ServerSocket.Connected) { ServerCommunication = new CommunicationBase(ServerSocket); // Receive server message while (!ModuleAbortEvent .WaitOne((int)TimeInterval.VeryVeryShortTime) || ServerSocket.Connected) { Receive(); } } } catch (Exception ex) { Log.ErrorEvent.Write(ex.Message); Thread.Sleep(60000); } } }
private void UpdateHardwareState(object sender, bool isconnected) { try { toolStrip1.Invoke((MethodInvoker)(() => { CommunicationBase communication = (CommunicationBase)sender; int index = toolStrip1.Items.IndexOfKey(communication.Id); if (index == -1) { index = toolStrip1.Items.Count; } else { toolStrip1.Items.RemoveAt(index); } if (isconnected) { ToolStripStatusLabel toolStripStatusLabel = new ToolStripStatusLabel(); toolStripStatusLabel.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; toolStripStatusLabel.Name = communication.Id; toolStripStatusLabel.Size = new System.Drawing.Size(73, 28); toolStripStatusLabel.Text = communication.Id; toolStripStatusLabel.Image = isconnected ? Properties.Resources.成功 : Properties.Resources.失败; toolStrip1.Items.Insert(index, toolStripStatusLabel); } })); } catch (Exception) { } }
public OtherVendorDevice(CommunicationBase comm, int slave_number, string name) { SlaveNumber = slave_number; DeviceName = name; IsSelectable = false; COMM = comm; }
private Byte[] mN_ToHex(string SmN) { int mN = int.Parse(SmN); string mNHex = Convert.ToString(mN, 16); string returnString = ""; string mNSendMessage = "F8FA0006000A4E756D626572" + mNHex.PadLeft(4, '0').ToUpper(); Byte[] crcByte = new byte[mNSendMessage.Length / 2]; for (int i = 0; i < mNSendMessage.Length; i = i + 2) { crcByte[i / 2] = Convert.ToByte(mNSendMessage.Substring(i, 2), 16); } CommunicationBase cb = new CommunicationBase(); ushort crc = cb.CRC16CCITT(crcByte); string crcString = crc.ToString("X2"); if (crc < 1000) { crcString = "0" + crc.ToString(); } returnString = mNSendMessage + crcString; Byte[] returnByte = new byte[returnString.Length / 2]; // string to byte. for (int i = 0; i < returnString.Length; i = i + 2) { returnByte[i / 2] = Convert.ToByte(returnString.Substring(i, 2), 16); } return(returnByte); }
/// <summary> /// 連線至主機 /// </summary> public void ConnectToServer() { //先建立IPAddress物件,IP為欲連線主機之IP IPAddress ipa = IPAddress.Parse(ConnectManager.ServerIP); //建立IPEndPoint IPEndPoint ipe = new IPEndPoint(ipa, ConnectManager.Port); //先建立一個TcpClient; TcpClient tcpClient = new TcpClient(); //開始連線 try { Debug.Log("主機IP=(" + ipa.ToString() + ") Port(" + ConnectManager.Port + ")"); Debug.Log("客戶端連線至主機中...\n"); tcpClient.Connect(ipe); if (tcpClient.Connected) { Debug.Log("客服端連線成功!"); CommunicationBase cb = new CommunicationBase(); cb.SendMsg("這是客戶端傳給主機的訊息", tcpClient); Debug.Log(cb.ReceiveMsg(tcpClient)); } else { Debug.Log("客服端連線失敗!"); } } catch (System.Exception ex) { tcpClient.Close(); Debug.Log(ex.Message); } }
private void ThSetting() { CommunicationBase cb = new CommunicationBase(); byte[] relockSendMsg = new byte[] { 0xF8, 0xFA, 0x00, 0x07, 0x00, 0x07, 0x52, 0x65, 0x61, 0x64, 0x02, 0x1B, 0x45 }; string relockReciveMsg = cb.Connection(relockSendMsg, Gip); if (relockReciveMsg != "") { relockReciveMsg = relockReciveMsg.Replace(" ", ""); int relockData = Convert.ToInt32(relockReciveMsg.Substring(12, 4), 16); StreamWriter sw = new StreamWriter(ipSettingPath, true); sw.WriteLine(GmN); sw.WriteLine(Gip); sw.WriteLine(GgateWay); sw.WriteLine(Gmask); sw.WriteLine(Gmac); sw.Dispose(); string[] ipArray = Gip.Split('.'); ipSettingPath = Application.StartupPath + "\\DeviceInfo_Setting\\" + ipArray[0].PadLeft(3, '0') + "." + ipArray[1].PadLeft(3, '0') + "." + ipArray[2].PadLeft(3, '0') + "." + ipArray[3].PadLeft(3, '0') + ".ini"; StreamWriter sw1 = new StreamWriter(ipSettingPath); sw1.WriteLine(relockData); sw1.Dispose(); } }
private void btnSend_Click(object sender, EventArgs e) { try { switch (cboSelectDevice.SelectedIndex) { case 0: this._comBase = this._k2601Control.CommunicationBase; break; case 2: this._comBase = this._dmmControl.CommunicationBase; break; default: this._comBase = null; break; } this._comBase.SendCmd(txtDataSend.Text); //txtReceive.Text = comBase.Receive(0); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public DMM6500Control(TcpSetting tcpSet) { this._communicationBase = new CommunicationBase(tcpSet); if (!this._communicationBase.Connect()) { throw this._communicationBase.Exception; } }
public DuplexImpl(CommunicationBase communicationBase) { _WaitDic = new Dictionary <Guid, DuplexWaitItem>(); _InstanceDic = new Dictionary <string, object>(); _HandlerList = new List <DuplexHandler>(); _CommunicationBase = communicationBase; }
public MPDAControl(TcpSetting tcpSet) { this._communication = new CommunicationBase(tcpSet); if (!this._communication.Connect()) { throw this._communication.Exception; } this._iOSet = new IOSetting(this._communication); }
/// <summary> /// Communicate /// </summary> public void Communicate() { try { CommunicationBase cb = new CommunicationBase(); string msg = cb.ReceiveMsg(this.mTcpClient); Debug.Log(msg + "\n"); cb.SendMsg("伺服器主機回傳訊息!", this.mTcpClient); } catch { Debug.Log("客戶端主動關閉連線!"); this.mTcpClient.Close(); } }
public void Communicate() { try { CommunicationBase comB = new CommunicationBase(); comB.SendMsg("You can send data", mclient); bool run = true; string[] allFile; int count = 0; while (run == true) { string receiveMsg = comB.ReadMessage(mclient); switch (receiveMsg) { case "": run = false; break; default: count++; allFile = receiveMsg.Split('\n'); List <string> bfile = allFile.ToList(); bfile.Remove(bfile.Last()); SendtoAzure(bfile); break; } } this.mclient.Close(); } catch { Trace.WriteLine("Client close the connection"); this.mclient.Close(); } }
/// <summary> /// 添加仪器 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void NewBtn_ClickAsync(object sender, RoutedEventArgs e) { //创建创建仪器对话框 var dialog3 = new InputDialog3(); dialog3.Model().Label1 = "Instrument Name"; dialog3.Model().Label3 = "Communication Type"; dialog3.Model().ItemsSource = new ObservableCollection <ComboBoxItemModel>(SystemSettings.Comm1); dialog3.Model().Input1 = ""; dialog3.Model().WarningMsg1 = "Input not available!"; dialog3.Model().Input1Validation = ( s => { return(!SystemSettings.InstrumentsList.Any(t => t.Name.ToUpper() == s.ToUpper())); }); Input: var result = await DialogHost.Show(dialog3, "RootDialog", new DialogClosingEventHandler((s, t) => { })); if ((bool)result) { var typeStr = ((ComboBoxItemModel)dialog3.Model().Input3).Name; var type = (CommunicationType)Enum.Parse(typeof(CommunicationType), typeStr); //仪器通讯类型错误则返回重新选择类型 if (type == CommunicationType.None) { await this.MsgBox("Please select the correct communication type."); goto Input; } var instr = new InstrumentModel() { Name = dialog3.Model().Input1, Description = dialog3.Model().Input1, CommnunicationType = type, Config = CommunicationBase.CreateCfg(type), CommReference = CommunicationBase.CreateCommunication(type) }; //添加仪器至全局变量 SystemSettings.InstrumentsList.Add(instr); //选中当前添加的仪器 Instruments.SelectedItem = instr; } }
public static void Main(string[] args) { Console.WriteLine("Testing RepositoryFileService."); string port = "8120"; string host = "http://localhost"; // start service CommunicationBase comObj = new CommunicationBase(Identity.Unidentified); CommMessage msg = new CommMessage(CommMessage.MessageType.Connect); msg.Arguments.Add("ARG1", "VAL1"); CommunicationObject obj = new CommunicationObject(null); msg.To = host + ":" + port; obj.PostMessage(msg); Console.WriteLine("Posting message to Repository."); }
private void StartConnection() { Byte[] sendStopMsgByte = new Byte[] { 0xFA }; //獲取 EPC/TID 號碼 Byte[] sandStartMsgByte = new Byte[] { 0xFA, 0xF8, 0x00, 0x05, 0x00, 0x06, 0xFF, 0x1D, 0x01, 0x01, 0xAE, 0x78 }; CommunicationBase cb = new CommunicationBase(); string reciveStopMsg = cb.Connection(sendStopMsgByte, labelP.Text); Thread.Sleep(50); string reciveStartMsg = cb.Connection(sandStartMsgByte, labelP.Text); this.Invoke((MethodInvoker) delegate { buttonConnect.Text = "已開啟"; buttonConnect.ForeColor = Color.Green; }); }
private void ReadUserInfo(object Oip_mN) { string ip_mN = (string)Oip_mN; string[] ip_mNArray = ip_mN.Split('@'); //取得Reader同卡間隔內不重複的Tag資料 Byte[] _SensorData = new Byte[] { 0xF8, 0xFA, 0x00, 0x00, 0x00, 0x02, 0xCB, 0x54 }; while (toRead) { CommunicationBase cb = new CommunicationBase(); string reciveText = cb.Connection(_SensorData, ip_mNArray[0]); if (reciveText.Length > 3) { WriteLog("◆卡號:" + cb.GetCardNumber(reciveText) + " ◆時間:" + cb.GetTime(reciveText) + " ◆機碼:" + ip_mNArray[1]); } } }
/// <summary> /// Connect to server /// </summary> public void ConnectToServer() { string hostIP = "127.0.0.1"; IPAddress ipa = IPAddress.Parse(hostIP); IPEndPoint ipe = new IPEndPoint(ipa, 1234); TcpClient tcpClient = new TcpClient(); try { Console.WriteLine("Server IP=" + ipa.ToString()); Console.WriteLine("Connecting...\n"); tcpClient.Connect(ipe); if (tcpClient.Connected) { Console.WriteLine("Connected!"); CommunicationBase cb = new CommunicationBase(); //cb.SendMsg("Register;username;password", tcpClient); //cb.SendMsg("LogIn;username;password1", tcpClient); //cb.SendMsg("AddSchedule;username;lot;max_lot_distance;max_wait_time", tcpClient); //cb.SendMsg("GetSchedule;username", tcpClient); //cb.SendMsg("UpdateColors;username;full_color;busy_color;free_color", tcpClient); cb.SendMsg("GetColors;username", tcpClient); Console.WriteLine(cb.ReceiveMsg(tcpClient)); } else { Console.WriteLine("Fail!"); } Console.Read(); } catch (Exception ex) { tcpClient.Close(); Console.WriteLine(ex.Message); Console.Read(); } }
private void UpdateHardwareState(object sender, bool isconnected) { try { toolStrip1.Invoke((MethodInvoker)(() => { CommunicationBase communication = (CommunicationBase)sender; foreach (var item in toolStrip1.Items) { ToolStripStatusLabel label = item as ToolStripStatusLabel; if (label != null && label.Alignment == ToolStripItemAlignment.Left && Hardware.Instance.hardwares.Find(hardware => hardware.Id == label.Name) == null) { toolStrip1.Items.Remove(label); } } int index = toolStrip1.Items.IndexOfKey(communication.Id); if (index == -1) { index = toolStrip1.Items.Count; ToolStripStatusLabel toolStripStatusLabel = new ToolStripStatusLabel(); toolStripStatusLabel.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right; toolStripStatusLabel.Name = communication.Id; //toolStripStatusLabel.Size = new System.Drawing.Size(73, 28); toolStripStatusLabel.Text = communication.Id; toolStripStatusLabel.BackColor = isconnected ? Color.LimeGreen : Color.Red; //toolStripStatusLabel.Image = IconImage.Get("成功"); toolStrip1.Items.Insert(index, toolStripStatusLabel); } else { ToolStripStatusLabel toolStripStatusLabel = toolStrip1.Items[index] as ToolStripStatusLabel; toolStripStatusLabel.BackColor = isconnected ? Color.LimeGreen : Color.Red; } })); } catch (Exception) { } }
public IOSetting(CommunicationBase com) { this._communication = com; this._byteCmd[0] = 0x51; this._byteCmd[1] = 0x00; }
public InstrumentBase(InstrumentModel instr) { Instrument = instr.CommReference; Instrument.Configuration = CommunicationBase.FormatConfiguration(instr.CommnunicationType, instr.Config); }
private Byte[] IP_Mask_Gateway_ToHex() { string returnString = ""; string mN = mN_Ip_Mask_Gateway.Split('|')[0]; string ip = mN_Ip_Mask_Gateway.Split('|')[1]; string mask = mN_Ip_Mask_Gateway.Split('|')[2]; string gateway = mN_Ip_Mask_Gateway.Split('|')[3]; string[] ipArray = ip.Split('.'); string[] maskArray = mask.Split('.'); string[] gatewayArray = gateway.Split('.'); for (int i = 0; i < ipArray.Length; i++) { string hex = Convert.ToString(Int32.Parse(ipArray[i]), 16).ToUpper(); if (hex.Length < 2) { returnString += "0" + hex; } else { returnString += hex; } } for (int i = 0; i < maskArray.Length; i++) { string hex = Convert.ToString(Int32.Parse(maskArray[i]), 16).ToUpper(); if (hex.Length < 2) { returnString += "0" + hex; } else { returnString += hex; } } for (int i = 0; i < gatewayArray.Length; i++) { string hex = Convert.ToString(Int32.Parse(gatewayArray[i]), 16).ToUpper(); if (hex.Length < 2) { returnString += "0" + hex; } else { returnString += hex; } } returnString = "F8FA0001000F00" + returnString; Byte[] crcByte = new byte[returnString.Length / 2]; for (int i = 0; i < returnString.Length; i = i + 2) { crcByte[i / 2] = Convert.ToByte(returnString.Substring(i, 2), 16); } Byte[] sendMessage = new byte[] { 0xF8, 0xFA, 0x00, 0x01, 0x00, 0x0F, 0x00, 0xC0, 0xA8, 0x01, 0x03, 0xFF, 0xFF, 0x00, 0x00, 0xC0, 0xA8, 0x01, 0xFE }; CommunicationBase cb = new CommunicationBase(); ushort crc = cb.CRC16CCITT(crcByte); string crcString = crc.ToString("X2"); if (crc < 1000) { crcString = "0" + crc.ToString(); } returnString = returnString + crcString; Byte[] returnByte = new byte[returnString.Length / 2]; for (int i = 0; i < returnString.Length; i = i + 2) { returnByte[i / 2] = Convert.ToByte(returnString.Substring(i, 2), 16); } return(returnByte); }
public PCS(CommunicationBase comm, int slave_number, string name, DictionaryBuilder dictionary) { SlaveNumber = slave_number; DeviceName = name; IsSelectable = true; COMM = comm; ObjectDictionary = dictionary; scopeControl = new ScopeControl(this); stateMachineDsp402 = new StateMachine(); EcStateMachine = EC_SM.EC_STATE_OPER; pdo_input_map = new PdoInput { statusword = 0, actual_position = 0, actual_velocity = 0, actual_torque = 0, modes_of_oper_disp = 0, digital_inputs = 0 }; pdo_output_map = new PdoOutput { controlword = 0, target_position = 0, target_velocity = 0, target_torque = 0, modes_of_oper = 0, digital_outputs = 0 }; Gauges = new ObservableCollection <GaugeItem>(); OmBits = new OMBitsLabel("No OM Selected", "SW Bit10", "SW Bit12", "SW Bit13"); ActualPosition = 0; CurrentCW = 0; CurrentMode = 0; timerNonRealTime.Elapsed += new ElapsedEventHandler(DoTimeEventNonRealTime); /*Non realtime relevant stuff*/ timerNonRealTime.Interval = 100; /* in milliseconds */ timerNonRealTime.Enabled = false; timerNonRealTime.AutoReset = true; Gauges.Add(new GaugeItem() { Name = "Temperature", Index = 0x200D, Subindex = 0x00, Unit = "°C", MinVal = 0, MaxVal = 120, DivisionsCount = 10, OptStart = 0, OptEnd = 85, DisplayFactor = 1 }); Gauges.Add(new GaugeItem() { Name = "DC Link Circuit Voltage", Index = 0x2079, Subindex = 0x01, Unit = "V", MinVal = 0, MaxVal = 76, DivisionsCount = 10, OptStart = 40, OptEnd = 60, DisplayFactor = 1000 }); EmcyMsgs = new ObservableCollection <EmergencyMessage> { new EmergencyMessage() { SequenceNumber = "0", EmcyMsgID = 0, Msg = "--" }, new EmergencyMessage() { SequenceNumber = "0", EmcyMsgID = 0, Msg = "--" }, new EmergencyMessage() { SequenceNumber = "0", EmcyMsgID = 0, Msg = "--" }, new EmergencyMessage() { SequenceNumber = "0", EmcyMsgID = 0, Msg = "--" }, new EmergencyMessage() { SequenceNumber = "0", EmcyMsgID = 0, Msg = "--" }, new EmergencyMessage() { SequenceNumber = "0", EmcyMsgID = 0, Msg = "--" }, new EmergencyMessage() { SequenceNumber = "0", EmcyMsgID = 0, Msg = "--" }, new EmergencyMessage() { SequenceNumber = "0", EmcyMsgID = 0, Msg = "--" }, }; }
/// <summary> /// 测试仪器连通情况 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Test_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrWhiteSpace(Command.Text)) { SetFail("Please input command first."); return; } var instr = ((InstrumentModel)Instruments.SelectedItem); //try //{ // IInstrumentHelper dd = new SteligentPW3256(); // dd.Open(instr); // dd.InvokeProc("SetVoltage", 12.0, "0", "1"); // dd.InvokeProc("PowerOn", null, null, "1"); // Thread.Sleep(500); // var dc = dd.InvokeProc<string>("MeasureVlotage", null, null, "1"); // SetSucess(dc); // dd.InvokeProc("PowerOff", null, null, "1"); // dd.Close(); //} //catch (Exception exp) //{ // var aa = ""; //} if (instr.CommReference == null) { SetFail("Instrument communication type error."); return; } try { instr.CommReference.Configuration = CommunicationBase.FormatConfiguration(instr.CommnunicationType, instr.Config); instr.CommReference.Open(); var cmd = Command.Text; switch ((TerminationCharacter)TerminationChar.SelectedValue) { case TerminationCharacter.LineFeed: cmd += "\n"; break; case TerminationCharacter.CarriageReturn: cmd += "\r"; break; case TerminationCharacter.LF_CR: cmd += "\r\n"; break; default: break; } instr.CommReference.SendData(cmd); if ((bool)IsReadDataBtn.IsChecked) { Thread.Sleep(Convert.ToInt32(Delay.Text)); var data = instr.CommReference.ReceiveData <string>(); SetSucess((bool)TrimBtn.IsChecked ? data?.Trim() : data); } else { SetSucess(""); } instr.CommReference.Close(); } catch (Exception exp) { instr.CommReference.Close(); SetFail(exp.Message.Trim()); } }
private void SchoolTime() { CommunicationBase cb = new CommunicationBase(); string week = ""; if (DateTime.Now.DayOfWeek.ToString().Equals("Monday")) { week = "01"; } else if (DateTime.Now.DayOfWeek.ToString().Equals("Tuesday")) { week = "02"; } else if (DateTime.Now.DayOfWeek.ToString().Equals("Wednesday")) { week = "03"; } else if (DateTime.Now.DayOfWeek.ToString().Equals("Thursday")) { week = "04"; } else if (DateTime.Now.DayOfWeek.ToString().Equals("Friday")) { week = "05"; } else if (DateTime.Now.DayOfWeek.ToString().Equals("Satursday")) { week = "06"; } else if (DateTime.Now.DayOfWeek.ToString().Equals("Sunday")) { week = "07"; } string date = DateTime.Now.ToString("yyyy MM dd " + week + " HH mm ss"); //date = "2017 04 11 02 16 13 00"; string[] dateArray = date.Split(' '); string dateHex = ""; for (int i = 0; i < dateArray.Length; i++) { if (i == 0) { for (int j = 0; j < dateArray[i].Length; j += 2) { dateHex += int.Parse(dateArray[i].Substring(j, 2)).ToString("X2").PadLeft(2, '0'); } } else { dateHex += int.Parse(dateArray[i]).ToString("X2").PadLeft(2, '0'); } } //for (int i = 0; i < dateArray.Length; i++) //{ // string temp = ""; // temp= int.Parse(dateArray[i]).ToString("X2"); // if (temp.Length == 3) // { // temp = temp.PadLeft(4, '0'); // } // else // { // temp = temp.PadLeft(2, '0'); // } // dateHex += temp; //} string beforeCRCMsg = "F8FC0000000A" + dateHex; byte[] CRCByte = new byte[beforeCRCMsg.Length / 2]; for (int i = 0; i < beforeCRCMsg.Length; i += 2) { CRCByte[i / 2] = Convert.ToByte(beforeCRCMsg.Substring(i, 2), 16); } ushort CRC = cb.CRC16CCITT(CRCByte); string afterCRCMsg = CRC.ToString("X2"); string sendMsg = /*"f8fc0000000a14140306050f2e2336a6"*/ beforeCRCMsg + afterCRCMsg.PadLeft(4, '0'); byte[] sendMsgByte = new byte[sendMsg.Length / 2]; for (int i = 0; i < sendMsg.Length; i += 2) { sendMsgByte[i / 2] = Convert.ToByte(sendMsg.Substring(i, 2), 16); } IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 50001); UdpClient uc = new UdpClient(); uc.Send(sendMsgByte, sendMsgByte.Length, ipep); byte[] receiveBytes = uc.Receive(ref ipep); uc.Dispose(); }
/// <summary> /// Receive client message /// </summary> /// <param name="Client"></param> private static void ReceiveClientRequest(object Client) { // Get the client connection configuration Socket ClientSock = (Client as Socket); CommunicationBase ClientCommunication = CommunicationDictionary[ClientSock]; string IPAddress = (ClientSock.RemoteEndPoint as IPEndPoint) .Address.ToString(); // Receive DiReCT message while (MasterSwitch && ClientSock.Connected) { try { // Receive DiReCT message byte[] Data = ClientCommunication.Receive(); // Convert data to json then parsing content string JsonString = Encoding.UTF8.GetString(Data); dynamic Json = JsonConvert.DeserializeObject(JsonString); if (Json["Type"] is "ControlSignal") { ReceiveEventArgs .ControlSignalEventArgs ControlSignalReceive = new ReceiveEventArgs.ControlSignalEventArgs { ControlSignal = Json["Data"], Socket = ClientSock }; Task.Run(() => { // do something }); } if (Json["Type"] is "DataFlow") { byte[] DataFlow = Encoding.UTF8.GetBytes(Json["Data"]); ReceiveEventArgs.DataFlowEventArgs DataFlowReceive = new ReceiveEventArgs.DataFlowEventArgs { Data = DataFlow, Socket = ClientSock }; Task.Run(() => { // do something }); } } catch (Exception ex) { Log.ErrorEvent.Write(ex.Message); } } // Disconnected or server service is ending // Release connection resources if (ModuleAbortEvent.WaitOne()) { SocketCloseSignal.WaitOne(); } CommunicationDictionary[ClientSock].Dispose(); CommunicationDictionary.Remove(ClientSock); ClientSock.Dispose(); Clients.Remove(ClientSock); ClientThreadList.Remove(Thread.CurrentThread); Log.GeneralEvent.Write("IP: " + IPAddress + " Close done"); }
/// <summary> /// 从仪器配置文件中读取所有仪器配置 /// </summary> private void LoadInstruments() { //SerialPort, //GPIB, //TCP, //USB, //UDP, object obj = null; InIHelper.FileName = SystemSettings.InstrumentIniFile; //Json转换条件,忽略空值属性 var jsSetting = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }; //读取所有设备字段信息-设备名称 foreach (var item in InIHelper.ReadSections()) { var cfg = InIHelper.Read(item, "Config", null); //读取配置 var typeStr = InIHelper.Read(item, "Type", null); //读取通信方式 if (Enum.IsDefined(typeof(CommunicationType), typeStr)) { var type = (CommunicationType)Enum.Parse(typeof(CommunicationType), typeStr, true);//格式化通讯方式为enum //根据不同通讯方式创建不同仪器实例信息 switch (type) { case CommunicationType.UDP: obj = JsonConvert.DeserializeObject <UdpCfgModel>(cfg, jsSetting); break; case CommunicationType.TCP: obj = JsonConvert.DeserializeObject <TcpIpCfgModel>(cfg, jsSetting); break; case CommunicationType.SerialPort: obj = JsonConvert.DeserializeObject <SerialPortCfgModel>(cfg, jsSetting); break; case CommunicationType.GPIB: obj = JsonConvert.DeserializeObject <GPIBCfgModel>(cfg, jsSetting); break; case CommunicationType.USB: obj = JsonConvert.DeserializeObject <USBCfgModel>(cfg, jsSetting); break; default: break; } var instr = new InstrumentModel() { Name = item, Config = obj, CommnunicationType = type, CommReference = CommunicationBase.CreateCommunication(type) }; //添加至系统全局变量中 SystemSettings.InstrumentsList.Add(instr); } } }
} // end ListenToConnect() /// <summary> /// Communicate /// </summary> private void Communicate(TcpClient mTcpClient) { try { CommunicationBase cb = new CommunicationBase(); string[] msg = cb.ReceiveMsg(mTcpClient).Split(';'); string result = "Error"; switch (msg[0]) { case "Register": if (UserList.Count(x => x.Account == msg[1]) == 0) { UserList.Add(new User() { Account = msg[1], Password = msg[2] }); result = "true"; } else { result = string.Format("false;User Account:{0} Exists!", msg[1]); } break; case "LogIn": if (UserList.Count(x => x.Account == msg[1] && x.Password == msg[2]) == 0) result = "false"; else result = "true"; break; case "UpdateColors": User colors = UserList.FirstOrDefault(x => x.Account == msg[1]); if (colors != null) { if (msg.Length == 5) { colors.ColorFull = msg[2]; colors.ColorBusy = msg[3]; colors.ColorFree = msg[4]; result = "true"; } else { result = "Incorrect format!"; } } else { result = "User Not Exist!"; } break; case "GetColors": User user = UserList.FirstOrDefault(x => x.Account == msg[1]); if (user != null) { result = string.Format("{0};{1};{2}", user.ColorFull, user.ColorBusy, user.ColorFree); } else { result = "User Not Exist!"; } break; case "AddSchedule": if (msg.Length == 5) { ScheduleList.Add(new Schedule() { Account = msg[1], Lot = msg[2], Distance = msg[3], Time = msg[4] }); result = "true"; } else { result = "Incorrect format!"; } break; case "GetSchedule": Schedule[] schedules = ScheduleList.Where(x => x.Account == msg[1]).ToArray(); result = ""; foreach (Schedule s in schedules) { result += string.Format("{0};{1};{2}@", s.Lot, s.Distance, s.Time); } break; default: result = "Unknown function: " + msg[0]; break; } cb.SendMsg(result, mTcpClient); } catch { Console.WriteLine("Client disconnected!"); mTcpClient.Close(); Console.Read(); } } // end Communicate()