TCPValve+Script

This script is an example of communicating with a hardware device using TCP/IP [|TCPValve.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;

// public class InstantTCPConnection {   // This method creates a connection and returns the network stream needed for communications. public bool GetTCPStream(string hostName, int port, out NetworkStream networkStream) {       if (m_tcpClient != null) {           try {               networkStream = m_tcpClient.GetStream; if (networkStream.CanWrite) {                   return true; }           }            catch {           }            m_tcpClient.Close; m_tcpClient = null; }       try {

m_tcpClient = new TcpClient; m_tcpClient.ExclusiveAddressUse=false; m_tcpClient.Connect(hostName, port);

networkStream = m_tcpClient.GetStream; if (networkStream.CanWrite) {               return true; }           m_tcpClient.Close; m_tcpClient = null; }       catch (Exception e)        { string error = string.Format("Error opening the TCP connection: {0}", e.ToString); Logger.Log(LogLevel.UserError, error, error); }       networkStream = null; return false; }   // This method is used to read a string from the network stream. String.Empty is returned on error. public string ReadString(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 info = string.Format("Read Data: {0} the received text is '{1}'", numberOfBytesRead, myCompleteMessage); Logger.Log(LogLevel.UserInfo, info, info); 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; }   // This method is used to write a string onto the network stream. public bool WriteString(NetworkStream stream, string message) {       try {           byte[] data = m_encoder.GetBytes(message); stream.Write(data, 0, data.Length);

string info = string.Format("Data sent: {0}", message); Logger.Log(LogLevel.UserInfo, info, info); return true; }       catch (Exception e)        { string error = string.Format("Error writing to the TCP connection: {0}", e.ToString); Logger.Log(LogLevel.Error, error); }

return false; }   // This is used to close the current tcp stream and connection. public void CloseTCPStream(NetworkStream stream) {       if (stream != null) {           stream.Close; }       if (m_tcpClient != null) {           m_tcpClient.Close; m_tcpClient = null; }   }    // This method is used to destroy this instance of the class. After calling this method, the instance cannot be used any more. public void Destroy {       if (m_tcpClient != null) {           m_tcpClient.Close; m_tcpClient = null; }       m_encoder = null; }   // The Members. private ASCIIEncoding m_encoder = new ASCIIEncoding; private TcpClient m_tcpClient; } // public class TCPDIO {   // This is called when a new value was set on the hardware item. public static bool SetParameter(Hardware hw, int rawValue) {       LocalizationHelper.SetThreadCulture; bool result = false; NetworkStream stream; if (m_connection.GetTCPStream("129.138.12.157", 1059, out stream)) {           string message = string.Format("{0} C", (rawValue == 0) ? "CLOSE" : "OPEN"); if (m_connection.WriteString(stream, message)) {               string response = m_connection.ReadString(stream); if (response == "ok") {                   m_lastSetValue = rawValue; result = true; }           }            m_connection.CloseTCPStream(stream); }       return result; }   // 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) {       lock (m_lock) {           if (!m_initialized) {               LocalizationHelper.SetThreadCulture; NetworkStream stream; if (m_connection.GetTCPStream("129.138.12.157", 1059, out stream)) {                   string message = "GetValveState C"; if (m_connection.WriteString(stream, message)) {                       m_initialized = true; string response = m_connection.ReadString(stream); if (response == "False") {                           m_lastSetValue = 0; //m_initialized = true; }                       else if (response == "True") {                           m_lastSetValue = 1; //m_initialized = true; }                   }                    m_connection.CloseTCPStream(stream); }           }        }        rawValue = m_lastSetValue; return true; }   // This is used to clean up and stop the script. public static void Dispose {       if (m_connection != null) {           m_connection.Destroy; m_connection = null; }       m_lock = null; }   // The private members. private static bool m_initialized; private static object m_lock = new object; private static int m_lastSetValue; private static InstantTCPConnection m_connection = new InstantTCPConnection; } code