Wednesday, June 16, 2010

Polling General Purpose Inputs with LLRP

In addition to triggering ROSpecs with general purpose inputs, you can also poll the state of GPIs with LLRP. This is useful when you want to trigger an external event based on the state of a GPI. For example, you might want to turn on an indicator light when a sensor is triggered. Polling works well if you only want to check the state of a GPI during a specific time. If you want to be notified of a state change at all times, an event-driven approach is better. I'll cover GPI events in a later post, but for now, here's what GPI polling looks like in C#.

First, download the Impinj LTK and add it to your project. Details on how to do this are covered in my "Hello World" LLRP post.

Add the library import statements at the top of your class.
using Org.LLRP.LTK.LLRPV1;
using Org.LLRP.LTK.LLRPV1.DataType;
using Org.LLRP.LTK.LLRPV1.Impinj;

Create a main function.
static LLRPClient reader;

static void Main(string[] args)
{
String state;
const int GPI_PORT = 1;

// Create a LLRPClient instance.
reader = new LLRPClient();

/*
Connect to the reader. 
Replace "SpeedwayR-10-25-32" with your reader's hostname. 
The second argument (2000) is a timeout value in milliseconds.
If a connection cannot be established within this timeframe, 
the call will fail.
*/
ENUM_ConnectionAttemptStatusType status;
reader.Open("SpeedwayR-10-25-32", 2000, out status);

// Check for a connection error
if (status != ENUM_ConnectionAttemptStatusType.Success)
{
// Could not connect to the reader.
// Print out the error
Console.WriteLine(status.ToString());
// Do something here.
// Your application should not continue.
return;
}

// Loop and poll the GPI state
while (true)
{
state = Get_GPI_State(GPI_PORT);
Console.WriteLine("GPI Port #" + GPI_PORT + " = " + state);
}
}

Then, create a function that will return the state of a GPI.
static String Get_GPI_State(int port)
{
String state = "";
MSG_ERROR_MESSAGE msg_err;
MSG_GET_READER_CONFIG msg = new MSG_GET_READER_CONFIG();
MSG_GET_READER_CONFIG_RESPONSE rsp =
reader.GET_READER_CONFIG(msg, out msg_err, 2000);
if (rsp != null)
{
// Success
// Get the GPI state
// GPIs are numbered 1-4,
// so subract one for the array index.
state = rsp.GPIPortCurrentState[port - 1].State.ToString();
}
else if (msg_err != null)
{
// Error
Console.WriteLine(msg_err.ToString());
}
else
{
// Timeout
Console.WriteLine("Timeout Error.");
}
return state;
}