Im trying to write a program that talks to a usb device. Opening the usb port and sending and receiving data is not the problem, the problem is sharing the connection to the usb across threads. I have button that willl send data entered in a text box to the device. What I want to be able to is to have a thread constantly checking usb connection for data incoming from the device and I want it to run and write its findings to a listbox while still allowing me the ability to send data when I want to.
I created a thread that executes a function that just sits in a loop listening for incoming data. The problem with this is that I start the thread after opening the usb connection and writing some data to the device. The usb connection is global so I am assuming that my poll function should be able to see it. Unfortunately although I know I assigned the global variable to a connection, the thread is reporting it as null and I cant open a new connection in the thread because only one connection can be opened to the device at a time.
The only solution I can think of using something like a mutex, where I would acquire rights to use the usb port when I want to write and when Im finished I would let go of it and allow the thread to acquire its own connection. That sounds like too much trouble than its worth. Please see code below.
Code:
private Thread workerThread = null;
UsbOtiNet usb = null;
public Form1()
{
...
}
.
.
private void btnRun_Click(object sender, System.EventArgs e)
{
Display ("--- Demo Starts ---");
// Create Object
UsbOtiNet usb = new UsbOtiNet();
// Connect to Reader
bool bOK;
bOK = usb.Open();
if (!bOK)
{
Display ("*** Failed connecting to Reader: " + usb.LastErrorString);
// Close Connection
usb.Close();
return;
}
Display ("Connect - OK");
// start listening for incoming usb traffic.
workerThread = new Thread(new ThreadStart(this.Poll));
workerThread.Start();
// Send ASCII Data
//byte[] baMODE0 = {0x4D,0x4F,0x44,0x45,0x30}; // binary representation of "MODE0"
string hexString = textBox1.Text;
int discarded;
byte[] baMODE0 = HexEncoding.GetBytes(hexString, out discarded);
// byte[] baMODE0 = {0x02,0x0A,0x00,0x3E,0xDF, 0x7E, 0x01, 0x01, 0x97, 0x03};
bOK = usb.Write(baMODE0);
if (!bOK)
{
Display ("*** Failed sending data to the Reader: " + usb.LastErrorString);
}
else
{
Display ("Write (" + hexString + ") - OK");
}
}
void Poll()
{
while(true)
{
if(usb != null)
{
usb.Timeout = 400;
// Read Data
int BytesRead = usb.Read(20);
if (BytesRead != 0)
Display ("Read() received: " + HexEncoding.ToString( usb.InputStream ));
}
else
Display("usb is {null}");
}
}
void Display (string msg)
{
int RowNumber = lstMsg.Items.Add (msg);
lstMsg.SelectedIndex = RowNumber;
}
private void Form1_Load(object sender, System.EventArgs e)
{
}
private void btnStop_Click(object sender, System.EventArgs e)
{
if(workerThread != null)
{
// stop the thread
workerThread.Abort();
}
// Close Connection
if(usb != null)
usb.Close();
Display ("--- Demo Ends ---");
Display ("");
}
}