You are here: Technical References > Remote Access to PLC Variables > Using the HTTP Interface with C# > Reading PLC Variables with C#

Reading PLC Variables with C#

This section illustrates how to read PLC"Programmable Logic Controller" A Programmable Logic Controller, PLC, or Programmable Controller is a digital computer used for automation of industrial processes, such as control of machinery on factory assembly lines. Used to synchronize the flow of inputs from (physical) sensors and events with the flow of outputs to actuators and events variables using the HTTP interface in C#. Three PLC variables (travelspeed, machinespeed, machinestate) are read in the following code snippet. The response can be either in JSON or text format, based on the request.

static void Main(string[] args)
{
string controllerIPAddress = "http://127.0.0.1"; // Replace this with your Controller IP address
string httpInterfaceURL = "/kas/plcvariables";
string format = "json"; // "text" is also supported //Framing GET request for PLC variables travelspeed, machinespeed and machinestate
string httpRequestString = controllerIPAddress + httpInterfaceURL + "?variables=travelspeed,machinespeed,machinestate&format=" + format;
WebClient client = new WebClient();
try
{
String httpResponseString = client.DownloadString(httpRequestString); // Send the GET HTTP request
if (format == "json")
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
// Use JavaScriptSerializer to convert the response string into JSON specific dictionary object
Dictionary<string, Dictionary<string, string>> responseDictionary = serializer.Deserialize<Dictionary<string, Dictionary<string, string>>>(httpResponseString);
// Now responseDictionary will contain a map of variable name and its attributes (that is value and errorstatus) Dictionary<string, string> attributeDictionary = new Dictionary<string, string>();
//To get get the value and errorstatus we can use the following way:
attributeDictionary = responseDictionary["travelspeed"];
string variableValue = attributeDictionary["value"];
string variableErrorStatus = attributeDictionary["errorstatus"];
Console.WriteLine("Variablename: travelspeed\nvalue:{0}\nerrorstatus={1}", variableValue, variableErrorStatus);
}
else // format == "text"
{
// The httpResponseString will contain comma separated values in the requested order
}
}
catch (WebException someWebException) // If server returns some error code
{
if (null != ((HttpWebResponse)someWebException.Response))
{
Stream reader = ((HttpWebResponse)someWebException.Response).GetResponseStream();
byte[] message = new byte[reader.Length];
reader.Read(message, 0, (int)reader.Length);
string httpErrorCode = someWebException.Message;
string httpErrorDescription = Encoding.ASCII.GetString(message);
}
}
catch (Exception someException) // If some other exception happens
{
string exceptionMessage = someException.Message;
}
}

 


Stay Connected with Kollmorgen

Copyright © 2015 Kollmorgen™