using System.Net; using System.Net.Sockets; using System.Text; using System.Text.RegularExpressions; namespace Estsh.Client.StepLibrary { public class RF182C { // Socket to realise TCP/IP conncetion private static Socket Connection = null; // connectet (true) or not (false) private bool ConnectionState = false; // buffer for received data public static String ReceiveBuffer = ""; // Indicator for an error in asynchronous receive threads public bool TagState =false; public bool AsyncError = false; public static string Message = ""; public static string BarCode = ""; //初始化 private string _editMessage = @"0025000000010001"; //写——前部分 private static string _write_F_Message = @"0000"; //写——后部分 private static string _write_B_Message = @""; //读--前部分 private string _Read_F_Message = @"0000"; //读——后部分 private string _Read_B_Message = @""; private static string _readMessage = @"00000028"; //连接 public bool Connect ( string editIP , int editPort ) { try { //Collect port and IP from the window. int port = 0; if ( Int32 .TryParse (editPort .ToString () , out port) == false || port <= 0 ) { Message = ( editIP + " is not a legal port" ); return false; } IPHostEntry hostEntry = null; hostEntry = Dns .GetHostEntry (editIP); foreach ( IPAddress address in hostEntry .AddressList ) { IPEndPoint ipe = new IPEndPoint (address , port); // stream based TCP/IP socket Socket tempSocket = new Socket (ipe .AddressFamily , SocketType .Stream , ProtocolType .Tcp); // the actual connect tempSocket .Connect (ipe); if ( tempSocket .Connected ) { Connection = tempSocket; Connection .ReceiveTimeout = 25; break; } } if ( Connection == null ) return false; //Start asynchronous receive ReceiveString s = new ReceiveString (); Connection .BeginReceive (s .buffer , 0 , ReceiveString .BufferSize , 0 , new AsyncCallback (ReceiveCallback) , s); ConnectionState = true; return true; } catch ( Exception ex ) { Message = ( "Connecting Failed - " + ex .Message ); return false; } } private void ReceiveCallback ( IAsyncResult res ) { try { if ( ConnectionState == true ) { // Collect data int size = Connection .EndReceive (res); ReceiveString s = ( ReceiveString ) res .AsyncState; lock ( ReceiveBuffer ) { //Store data in buffer ReceiveBuffer += Encoding .ASCII .GetString (s .buffer , 0 , size); } //Start new asynchronous receive ReceiveString rs = new ReceiveString (); Connection .BeginReceive (rs .buffer , 0 , ReceiveString .BufferSize , 0 , new AsyncCallback (ReceiveCallback) , rs); } } catch ( Exception ex ) { // An error occured --> report it AsyncError = false; Message = ( ex .Message ); } } //初始化 public bool Initialization () { bool result= Send (_editMessage); return result; } //写信息 public static bool Write ( string barcode ) { string SN = string.Empty; if (barcode.Length <= 40) { SN = barcode.PadRight(40, '*'); } else { SN = barcode; } //转ASCII byte[] array = System.Text.Encoding.ASCII.GetBytes(SN); //数组array为对应的ASCII数组 string ASCIIstr2 = null; for ( int i = 0 ; i < array .Length ; i++ ) { int asciicode = ( int ) ( array [ i ] ); ASCIIstr2 += Convert .ToString (asciicode);//字符串ASCIIstr2 为对应的ASCII字符串 } string a = _write_F_Message + ASCIIstr2 + _write_B_Message; bool result = Send (a); //ReceiveBuffer = ""; return result; } //写信信息为空 public bool WriteNull(string barcode) { string SN = string.Empty; SN = barcode; //转ASCII byte[] array = System.Text.Encoding.ASCII.GetBytes(SN); //数组array为对应的ASCII数组 string ASCIIstr2 = null; for (int i = 0; i < array.Length; i++) { int asciicode = (int)(array[i]); ASCIIstr2 += Convert.ToString(asciicode);//字符串ASCIIstr2 为对应的ASCII字符串 } string a = _write_F_Message + ASCIIstr2 + _write_B_Message; bool result = Send(a); //ReceiveBuffer = ""; return result; } //读信息 public static bool read () { //ASCII转字符串 bool result = Send (_readMessage); string str1 = string .Empty; //string str = ReceiveBuffer.ToString(); if ( ReceiveBuffer .ToString () == "" ) { Message = "读取信息出错"; } int z=0; for ( int i = 1 ; i > z ; i++ ) { if ( ReceiveBuffer .ToString () != "" ) { z = i + 1; } } Thread.Sleep(79); string a =""; Regex reg_2 = new Regex ("(?i)(?<=)[^\"]*(?=)"); MatchCollection mc2 = reg_2 .Matches (ReceiveBuffer); foreach ( Match m in mc2 ) { a += m .Value; } Thread.Sleep(79); if ( a .ToString () != "" ) { string t2 = "0000"; if ( !a .Contains (t2) ) { Message = "读取信息出错"; return false; } } string b = ""; Regex reg = new Regex ("(?i)(?<=)[^\"]*(?=)"); MatchCollection mc = reg .Matches (ReceiveBuffer); foreach ( Match m in mc ) { b += m .Value; } Thread.Sleep(79); for ( int i = 0 ; i < b .Length - 1 ; i++ ) { string subStr = b.Substring(i, 2); //00是终止符 if (subStr != "00") { int j = int.Parse(subStr); str1 += Encoding.ASCII.GetString(new byte[] { (byte)j }); i++; } else { i++; } } Thread.Sleep(219); BarCode = str1.Replace("/0", ""); BarCode = BarCode.Replace("*", ""); //ReceiveBuffer = ""; if ( BarCode == "" ) { result = false; } else { result = true; } return result; } //发送命令 public static bool Send ( string editMessage ) { if ( editMessage != "" ) { byte[] buffer = Encoding .ASCII .GetBytes (editMessage .ToCharArray ()); try { int count = Connection .Send (buffer); if ( count != buffer .Length ) { Message = ( "Sending failed!" ); return false; } } catch ( Exception ex ) { Message = ( ex .Message ); return false; } } System .Threading .Thread .Sleep (100); return true; } /// /// 判断是否连接成功 /// /// public bool IsConnected () { try { if ( TagState .ToString () .ToUpper () == "YES" ) { return true; } return false; } catch { return false; } } //检测是否有TAG public void ParseBuffer () { //bool TAGState = false; lock ( ReceiveBuffer ) { for ( XMLTag tag = FirstTag () ; tag != null ; tag = FirstTag () ) { String message = ReceiveBuffer .Substring (tag .startIndex , tag .length); AppendInMessage (message); ReceiveBuffer = ReceiveBuffer .Substring (tag .startIndex + tag .length); if ( message .Contains ("") ) { if ( message .Contains ("0000") ) { //未检测到TAG SetTagDetectionState (TagDetectionState .NO); //TAGState = false; } else { //检测到TAG SetTagDetectionState (TagDetectionState .YES); //TAGState = true; } } } } //return TAGState; } public void Disconnect () { try { Connection .Disconnect (false); SetConnectionState (false); Connection .Close (); } catch ( Exception ex ) { } } private XMLTag FirstTag () { int index1 = ReceiveBuffer .IndexOf (""); int index2 = ReceiveBuffer .IndexOf (""); int index3 = ReceiveBuffer .IndexOf (""); if ( index1 == -1 && index2 == -1 && index3 == -1 ) return null; //No XML tag found if ( index1 == -1 ) index1 = Int32 .MaxValue; if ( index2 == -1 ) index2 = Int32 .MaxValue; if ( index3 == -1 ) index3 = Int32 .MaxValue; String endTag = ""; XMLTag tag = new XMLTag (); tag .type = "alarm"; tag .startIndex = index3; if ( index1 < index2 && index1 < index3 ) { endTag = ""; tag .type = "reply"; tag .startIndex = index1; } else if ( index2 < index3 ) { endTag = ""; tag .type = "notification"; tag .startIndex = index2; } int endIndex = ReceiveBuffer .IndexOf (endTag , tag .startIndex); if ( endIndex == -1 ) return null; tag .length = endIndex - tag .startIndex + endTag .Length; return tag; } private void AppendInMessage ( String message ) { message = message .Replace ("\r" , ""); message = message .Replace ("\n" , ""); Message = ( "IN : " + message ); } private void SetConnectionState ( bool state ) { if ( state == true ) { ConnectionState = true; AsyncError = true; } else { ConnectionState = false; SetTagDetectionState (TagDetectionState .UNDEFINED); TagState = false; ParseBuffer (); AsyncError = false; } } private void SetTagDetectionState ( TagDetectionState state ) { switch ( state ) { case TagDetectionState .YES: Message = "TAG(s) DETECTED"; TagState = true; break; case TagDetectionState .NO: Message = "NO TAG DETECTED"; TagState = false; break; case TagDetectionState .UNDEFINED: Message = ""; //Color of the dialog TagState = false; break; } } } enum TagDetectionState { YES , NO , UNDEFINED } internal class ReceiveString { public readonly static int BufferSize = 512; public byte[] buffer = new byte [ BufferSize ]; } internal class XMLTag { //Index of first character public int startIndex; //Block length public int length; // Type ( reply, notification or alarm, since only telegramms // from the ASM are handeld within this structure) public String type; } }