EMS RFID Communication
ไหมไทย :: C# Programming :: General
หน้า 1 จาก 1
EMS RFID Communication
- Code:
/*
* Created by SharpDevelop.
* User: psupawa@gmail.com
* Date: 16-Oct-14
* Time: 9:02 AM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Globalization;
namespace emsRFID
{
/// <summary>
/// Program communicate to the serial port.
/// </summary>
public partial class MainForm : Form
{
private SerialPort ComPort = new SerialPort();
internal delegate void SerialDataReceivedEventHandlerDelegate(
object sender, SerialDataReceivedEventArgs e);
internal delegate void SerialPinChangedEventHandlerDelegate(
object sender, SerialPinChangedEventArgs e);
delegate void SetTextCallback(string text);
private string InputData = String.Empty;
private int commandCode = 0;
private System.Timers.Timer timer;
private System.Threading.Timer readTimer = null;
private System.Threading.TimerCallback cb;
private bool readExpired = false;
private string rcvString = "";
private string commandString;
private string[] commandList = {
"123456789012345678901234567A",
"123456789012345678901234567B",
"123456789012345678901234567C",
"123456789012345678901234567D",
"123456789012345678901234567E",
"123456789012345678901234567F",
"123456789012345678901234567G",
"123456789012345678901234567H",
"123456789012345678901234567I",
"123456789012345678901234567J",
"123456789012345678901234567K",
"123456789012345678901234567L",
"123456789012345678901234567M",
"123456789012345678901234567N",
"123456789012345678901234567U",
"123456789012345678901234567P",
"123456789012345678901234567Q",
"123456789012345678901234567R",
"123456789012345678901234567S",
"123456789012345678901234567T"
};
private DateTime writeStart = DateTime.UtcNow;
private Label[] lblReadStatus = new Label[20];
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
ComPort.DataReceived += new SerialDataReceivedEventHandler(PortDataReceived);
//
// TODO: Add constructor code after the InitializeComponent() call.
//
GetPort();
TimerConfig();
CreateReadStatusLabel();
}
private void CreateReadStatusLabel() {
var n = 20;
for (int i = 0; i < n; i++)
{
//Create label
lblReadStatus[i] = new Label();
lblReadStatus[i].BackColor = Color.LightGray;
//Position label on screen
lblReadStatus[i].Left = (i * 20) + 110;
lblReadStatus[i].Top = 210;
lblReadStatus[i].Width = 16;
lblReadStatus[i].Height = 16;
//Add controls to form
this.Controls.Add(lblReadStatus[i]);
}
}
private void TimerConfig() {
cb = new System.Threading.TimerCallback (ProcessTimerEvent);
//readTimer = new System.Threading.Timer (cb, time, 1000, 100);
timer = new System.Timers.Timer();
timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimerFired);
timer.Interval = 2000;
}
private void ProcessTimerEvent (object obj)
{
readTimer.Dispose();
readExpired = true;
MessageBox.Show ("No response from device.", "Alert");
}
private void OnTimerFired(object Sender, System.Timers.ElapsedEventArgs e)
{
timer.Stop();
if ((commandCode == 3)||(commandCode == 9)) { // Write Tag
//MessageBox.Show ("Write error, No response from device.", "Alert");
DialogResult userAction = MessageBox.Show("Write error, No response from device.\nPlease put back the RFID Tag.", "Alert",
MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
if (userAction == DialogResult.OK) {
SendCommand(commandCode, commandString);
}
else {
textMessage.Text = "Your decision will effect incompleted data written to the RFID Tag.\n";
}
}
else {
CloseConnection("OnReadTimerFired, no response from device.");
}
}
private void ButtonConnectClick(object sender, EventArgs e)
{
ComPort.PortName = Convert.ToString(port.Text);
ComPort.BaudRate = Convert.ToInt32(baudRate.Text);
ComPort.DataBits = Convert.ToInt16(dataBit.Text);
ComPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stopBit.Text);
ComPort.Parity = (Parity)Enum.Parse(typeof(Parity), parity.Text);
//ComPort.Encoding = Encoding.GetEncoding(28591); // same as ISO-8859-1
ComPort.Encoding = Encoding.GetEncoding("ISO-8859-1");
ComPort.ReadTimeout = 1000;
ComPort.WriteTimeout = 1000;
ComPort.NewLine = "0x03";
try {
ComPort.Open();
ChangeStatus(false);
lblStatus.BackColor = Color.Green;
textMessage.Text = "Connected.\n";
}
catch (Exception ex) {
textMessage.Text = "Error: "+ex.Message+"\n";
lblStatus.BackColor = Color.Red;
}
}
private void ButtonDisconnectClick(object sender, EventArgs e)
{
CloseConnection("user close");
}
private void CloseConnection(string message)
{
textMessage.AppendText("Disconnect, "+message+"\n");
ChangeStatus(true);
lblStatus.BackColor = Color.White;
if (ComPort.IsOpen)
ComPort.Close();
}
private void GetPort() {
string[] ArrayComPortsNames = null;
int index = -1;
string ComPortName = null;
//Com Ports
ArrayComPortsNames = SerialPort.GetPortNames();
do
{
index += 1;
port.Items.Add(ArrayComPortsNames[index]);
} while (!((ArrayComPortsNames[index] == ComPortName) ||
(index == ArrayComPortsNames.GetUpperBound(0))));
Array.Sort(ArrayComPortsNames);
if (index == ArrayComPortsNames.GetUpperBound(0))
{
ComPortName = ArrayComPortsNames[0];
}
//get first item print in text
port.Text = ArrayComPortsNames[0];
}
private void ChangeStatus(Boolean newStatus) {
btnConnect.Enabled = newStatus;
btnDisconnect.Enabled = !newStatus;
port.Enabled = newStatus;
baudRate.Enabled = newStatus;
dataBit.Enabled = newStatus;
stopBit.Enabled = newStatus;
parity.Enabled = newStatus;
btnSearchTag.Enabled = !newStatus;
RFIDCommuication(btnSearchTag.Enabled && btnConnect.Enabled);
}
private void RFIDCommuication(bool newStatus) {
btnRead.Enabled = newStatus;
btnWrite.Enabled = btnConnect.Enabled && btnSearchTag.Enabled;
btnClearTag.Enabled = newStatus;
btnClearAll.Enabled = newStatus;
btnWriteAll.Enabled = newStatus;
btnReadAll.Enabled = newStatus;
btnReadTagID.Enabled = newStatus;
dataText.Enabled = newStatus;
cbPocket.Enabled = newStatus;
for (int i = 0; i < 20; i++)
{
lblReadStatus[i].BackColor = (newStatus) ? Color.White : Color.LightGray;
}
}
private void PortDataReceived(object sender, SerialDataReceivedEventArgs e)
{
InputData = ComPort.ReadExisting();
if (InputData != String.Empty)
{
this.BeginInvoke(new SetTextCallback(SetText), new object[] { InputData });
}
}
private void SetText(string text)
{
rcvString += text; // loop receive data
try {
string rcvText = ConvertStringToHex(rcvString).ToUpper();
string asciiText = ConvertHexToString(rcvText);
// 0x03 end of transmission message
if (rcvString.EndsWith(Convert.ToString((char)3))) {
//if (readTimer != null) readTimer.Dispose();
timer.Stop();
rcvString = "";
if (commandCode == 0) { // Search Tag
rcvText = asciiText.Substring(1, asciiText.Length-2);
//dataText.Text = ConvertStringToHex(rcvText).ToUpper();
if ("AA08FFFF".Equals(ConvertStringToHex(rcvText).ToUpper())) {
RFIDCommuication(true);
}
}
else if (commandCode == 9) { // Write all
rcvText = asciiText.Substring(1, asciiText.Length-2);
// check if return code is write complete
if ("AA06FFFF".Equals(ConvertStringToHex(rcvText).ToUpper())) {
// check if not last unit
if (cbPocket.SelectedIndex < 19) {
// write next unit
cbPocket.SelectedIndex++;
int idx = cbPocket.SelectedIndex;
SendCommand(9, GetWriteTagCommand(idx + 1, commandList[idx]));
}
else {
DateTime writeStop = DateTime.UtcNow;
textMessage.AppendText("Write complete["+cbPocket.SelectedIndex+"]: " + writeStop.ToLocalTime().ToString("dd-MMM-yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture) + "\n");
textMessage.AppendText("Write elapse: " + (writeStop - writeStart) + "\n");
}
}
else {
textMessage.AppendText("Write error["+cbPocket.SelectedIndex+"]: " + ConvertStringToHex(rcvText).ToUpper() + "\n");
}
}
else if (commandCode == { // Read all
rcvText = asciiText.Substring(1, asciiText.Length-2);
// check if return code is read complete
if (ConvertStringToHex(rcvText).ToUpper().StartsWith("AA05")) {
textMessage.AppendText("Received["+cbPocket.SelectedIndex+"]: " + asciiText + "\n");
lblReadStatus[cbPocket.SelectedIndex].BackColor = (asciiText.Length > 6) ? Color.Green : Color.Red;
// check if not last unit
if (cbPocket.SelectedIndex < 19) {
// write next unit
cbPocket.SelectedIndex++;
int idx = cbPocket.SelectedIndex;
SendCommand(8, GetReadTagCommand((idx+1), 28));
}
else {
DateTime writeStop = DateTime.UtcNow;
textMessage.AppendText("Read complete["+cbPocket.SelectedIndex+"]: " + writeStop.ToLocalTime().ToString("dd-MMM-yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture) + "\n");
textMessage.AppendText("Read elapse: " + (writeStop - writeStart) + "\n");
}
}
else {
textMessage.AppendText("Read error["+cbPocket.SelectedIndex+"]: " + ConvertStringToHex(rcvText).ToUpper() + "\n");
}
}
else if (commandCode == 2) { // Read tag
rcvText = asciiText.Substring(3, asciiText.Length-6);
dataText.Text = rcvText;
lblReadStatus[cbPocket.SelectedIndex].BackColor = (asciiText.Length > 6) ? Color.Green : Color.Red;
}
else { // Read Tag ID, write tag, clear tag
textMessage.AppendText("Received: " + ConvertStringToHex(asciiText).ToUpper() + "\n");
}
}
}
catch (Exception ex) {
textMessage.AppendText("SetText(), error: " + ex.Message + "\n");
}
}
private void BtnSearchTagClick(object sender, EventArgs e)
{
if (!readExpired) {
SendCommand(0, GetSearchTagCommand());
}
else {
CloseConnection("no response from device.");
}
}
private void BtnReadTagIDClick(object sender, EventArgs e)
{
SendCommand(1, GetReadTagIdCommand());
}
void BtnClearTagClick(object sender, EventArgs e)
{
SendCommand(4, GetClearTagCommand(Convert.ToInt32(cbPocket.Text), 28));
}
void BtnClearAllClick(object sender, EventArgs e)
{
SendCommand(5, GetClearTagCommand());
}
private void BtnReadClick(object sender, EventArgs e)
{
// read port
string outString = "";
outString = GetReadTagCommand(Convert.ToInt32(cbPocket.Text), 28);
SendCommand(2, outString);
}
private void BtnWriteClick(object sender, EventArgs e)
{
SendCommand(3, GetWriteTagCommand(Convert.ToInt32(cbPocket.Text), dataText.Text));
}
private void BtnWriteAllClick(object sender, EventArgs e)
{
writeStart = DateTime.UtcNow;
cbPocket.SelectedIndex = 0;
textMessage.AppendText("Write start["+cbPocket.SelectedIndex+"]: " + writeStart.ToLocalTime().ToString("dd-MMM-yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture) + "\n");
int idx = cbPocket.SelectedIndex;
SendCommand(9, GetWriteTagCommand(idx + 1, commandList[idx]));
}
private void BtnReadAllClick(object sender, EventArgs e)
{
writeStart = DateTime.UtcNow;
cbPocket.SelectedIndex = 0;
textMessage.AppendText("Read start["+cbPocket.SelectedIndex+"]: " + writeStart.ToLocalTime().ToString("dd-MMM-yyyy HH:mm:ss.fff", CultureInfo.InvariantCulture) + "\n");
int idx = cbPocket.SelectedIndex;
SendCommand(8, GetReadTagCommand((idx+1), 28));
}
private void DataTextTextChanged(object sender, EventArgs e)
{
btnWrite.Enabled = (dataText.Text.Length == 28);
}
private void SendCommand(int cmdCode, string outString)
{
ComPort.DiscardOutBuffer();
ComPort.DiscardInBuffer();
commandCode = cmdCode;
commandString = outString;
if (ComPort.IsOpen) {
//textMessage.AppendText("Send: "+ConvertStringToHex(outString).ToUpper()+"\n");
try {
ComPort.Write(outString);
timer.Start();
}
catch (Exception ex) {
//readTimer.Enabled = false;
if (readTimer != null) readTimer.Dispose();
textMessage.AppendText("Error: "+ex.Message+"\n");
CloseConnection(ex.Message);
}
}
else {
textMessage.AppendText("Error: COMM Port is closed\n");
}
}
private void ReadData() {
string rcvString = ComPort.ReadExisting();
textMessage.AppendText("Receive: "+ConvertStringToHex(rcvString).ToUpper()+"\n");
dataText.Text = rcvString;
}
private string GetClearTagCommand() {
return GetClearTagCommand(1);
}
private string GetClearTagCommand(int position) {
return GetClearTagCommand(1,0);
}
private string GetClearTagCommand(int position, int len) {
string cmdString = "";
cmdString += getActionCommand("04"); // Fill tag action
cmdString += getAddressCommand(position); // Write address
cmdString += getReadWriteLengthCommand(len); // Write length
cmdString += getTimeoutCommand(); // Timeout
string dataCmd = "";
for (int i = 0; i < 2; i++) dataCmd += Convert.ToChar(0); // Fill null value
cmdString += dataCmd;
cmdString += getTerminatorCommand(); // Terminator
return cmdString;
}
private string GetWriteTagCommand(int position, string data) {
string cmdString = "";
int len = data.Length;
cmdString += getActionCommand("06"); // Write action
cmdString += getAddressCommand(position); // Write address
cmdString += getReadWriteLengthCommand(len); // Write length
cmdString += getTimeoutCommand(); // Timeout
string dataCmd = "";
for (int i = 0; i < data.Length; i++)
{
dataCmd += Convert.ToChar(0) + data.Substring(i, 1); // data
}
cmdString += dataCmd;
cmdString += getTerminatorCommand(); // Terminator
return cmdString;
}
private string GetReadTagCommand(int position, int len) {
string cmdString = "";
cmdString += getActionCommand("05"); // Read action
cmdString += getAddressCommand(position); // Read address
cmdString += getReadWriteLengthCommand(len); // Read length
cmdString += getTimeoutCommand(); // Timeout
cmdString += getTerminatorCommand(); // Terminator
return cmdString;
}
private string GetReadTagIdCommand() {
string cmdString = "";
cmdString += getActionCommand("07"); // Read tag ID action
cmdString += getTimeoutCommand(); // Timeout
cmdString += getTerminatorCommand(); // Terminator
return cmdString;
}
private string GetSearchTagCommand() {
string cmdString = "";
cmdString += getActionCommand("08"); // Search tag action
cmdString += getTimeoutCommand(); // Timeout
cmdString += getTerminatorCommand(); // Terminator
return cmdString;
}
private string getActionCommand(int intAction) {
return getActionCommand(ConvertHexToString(ConvertAsciiToHex(intAction))); // Perform action
}
private string getActionCommand(string hexAction) {
return ConvertHexToString("AA") + ConvertHexToString(hexAction); // Perform action
}
private string getAddressCommand(int position) {
int addr = ((position - 1) * 32) + 5;
return "" + Convert.ToChar(addr / 256) + ConvertHexToString(ConvertAsciiToHex(addr % 256)); // address
}
private string getTimeoutCommand() {
return ConvertHexToString("07") + ConvertHexToString("D0"); // Timeout value (2 seconds)
}
private string getTerminatorCommand() {
return ConvertHexToString("FF") + ConvertHexToString("FF"); // Message terminator
}
private string getReadWriteLengthCommand(int len) {
return "" + Convert.ToChar(len / 256) + Convert.ToChar(len % 256); // Read/Write length
}
private string ConvertStringToHex(string asciiString)
{
string hex = "";
foreach (char c in asciiString)
{
int tmp = c;
hex += String.Format("{0:x2}", (uint)Convert.ToUInt32(tmp.ToString()));
}
return hex;
}
private string ConvertHexToString(string HexValue)
{
string StrValue = "";
uint ascii = 0;
while (HexValue.Length > 0)
{
ascii = Convert.ToUInt32(HexValue.Substring(0, 2), 16);
if (ascii != 0)
StrValue += Convert.ToChar(ascii).ToString();
HexValue = HexValue.Substring(2, HexValue.Length - 2);
}
return StrValue;
}
private int ConvertHexToInt(string HexValue)
{
int i = (int)Convert.ToUInt32(HexValue.Substring(0, 2), 16);
return i;
}
private string ConvertAsciiToHex(int asciiValue)
{
string hex = "";
if ((asciiValue < 0) || (asciiValue > 255)) {
hex = "??";
}
else if (asciiValue == 0) {
hex = "00";
}
else {
hex = String.Format("{0:x2}", (uint)Convert.ToUInt32(asciiValue.ToString()));
}
return hex;
}
}
}
ไหมไทย :: C# Programming :: General
หน้า 1 จาก 1
Permissions in this forum:
คุณไม่สามารถพิมพ์ตอบ
|
|