TCPServer

An example of embedding a TCPServer into Qtegra to listen for incoming commands from the outside world [|TCPServer.cs] code format="csharp" // RegisterAssembly: BasicHardware.dll // RegisterAssembly: plugin\HardwareScript.if.dll // RegisterSystemAssembly: System.dll

using System.Net; using System.Net.Sockets; using System.Text; using System.IO; using Thermo.Imhotep.BasicHardware; using Thermo.Imhotep.HardwareScript; using Thermo.Imhotep.Util; using Thermo.Imhotep.HardwareClientNS;

// public class TCPServer {

public const int Open = 1;

public const int Close = 0;

// This is called when a new value was set on the hardware item. // start or stop the server public static bool SetParameter(Hardware hw, int rawValue) {

bool result = true;

// start a new thread and server forever if (rawValue==1) {           //Thread thread=new Thread(new ThreadStart(ServerForever)); //thread.Start; ServerForever; //m_initialized=true; //result=true;

}       else {

//m_initialized=false;

//result=false; listener.Stop; }       return result; }

private static void ServerForever {       listener=new TcpListener(IPAddress.Any,m_port);

listenThread=new Thread(new ThreadStart(Listen)); listenThread.Start; }   private static void Listen {

string info="Listening";

Logger.Log(LogLevel.UserInfo, info, info); listener.Start;

while(true) {           TcpClient client=listener.AcceptTcpClient;

Thread clientThread = new Thread(new ParameterizedThreadStart(HandleCmd)); clientThread.Start(client); }   }    private static void HandleCmd(object client) {       TcpClient tcpClient = (TcpClient)client; //NetworkStream clientStream = tcpClient.GetStream;

string response=ReadCmd(tcpClient.GetStream); tcpClient.Close;

ParseAndExecuteCommand(response);

}   private static string ReadCmd(NetworkStream stream) {       int BufferSize = 1024; byte[] data = new byte[BufferSize]; try {           StringBuilder myCompleteMessage = new StringBuilder; int numberOfBytesRead = 0;

// Incoming message may be larger than the buffer size. do           { numberOfBytesRead = stream.Read(data, 0, data.Length);

myCompleteMessage.AppendFormat("{0}", Encoding.ASCII.GetString(data, 0, numberOfBytesRead)); }           while (stream.DataAvailable);

string rd = string.Format("Read Data: {0} the received text is '{1}'", numberOfBytesRead, myCompleteMessage); Logger.Log(LogLevel.UserInfo, rd, rd); return myCompleteMessage.ToString; }       catch (Exception e)        { string error = string.Format("Could not read from the NetworkStream. {0}", e.ToString); Logger.Log(LogLevel.UserError, error, error); }       return string.Empty; }   private static void ParseAndExecuteCommand(string cmd) {       //        //    Expected command format //       // ValveName.Action // ie E.open string[] args = cmd.Split(':'); switch (args[0]) {           case "Valve": string[] vargs = args[1].Split('.'); int action; if (vargs[1]=="open") {                   action = Open; }               else {                   action = Close; }               ArgusMC.SetParameter("Valve "+vargs[0], action); break; case "SetMass": int ufc=1; int counter=1; double integrationTime = 131.072;       // time in millisec int settlingTime = 20;                   // time in millisec //ArgusMC.RunSingleMeasurementScan((float)args[1], (int)integrationTime, settlingTime, ufc, counter, "");

double mass;

if(!Double.TryParse(args[1], out mass))

{

Logger.Log(LogLevel.Error, "Could not read out the mass value.");

}

else

{

ArgusMC.ScanTransitionController.RunSingleScan(mass, integrationTime, settlingTime);

}               break; }   }    // This is called to get the last set value for this item. This method is called periodically. public static bool GetParameter(Hardware hw, out int rawValue) {

rawValue=0; return true; }

public static bool Sleep(int seconds, string text)

{

int numLoop = 0;

bool showText = !string.IsNullOrEmpty(text);

while (numLoop < seconds)

{

Thread.Sleep(1000);

if (showText)

{

//m_information = String.Format(text + "{0} s: {1}", seconds, numLoop);

}

//if (m_abort)

//{

//   return false;

//}

++numLoop;

}

return true;

}   // The private members. private static bool m_initialized;

private static TcpListener listener; private static Thread listenThread; private static int m_port =1059;

} code