0% found this document useful (0 votes)
12 views

Form1 Cs

The document discusses code for connecting a reader device to a PLC via a tunnel. It includes functions for initializing the connection, clearing tag lists, setting the reader configuration, and handling connection and device state events.

Uploaded by

Shahzad Malik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Form1 Cs

The document discusses code for connecting a reader device to a PLC via a tunnel. It includes functions for initializing the connection, clearing tag lists, setting the reader configuration, and handling connection and device state events.

Uploaded by

Shahzad Malik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 16

using Rovinj.

Device;
using Rovinj.Reader;
using Rovinj.Reader.Silion;
using Rovinj.Tunnel;
using Rovinj.Tunnel.Plc;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Media;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
using TunnelDemo.Properties;

namespace TunnelDemo
{
public partial class Form1 : Form
{
private ITunnel tunnel;
private bool isAutoMode;//???????
private List<string> epcList = new List<string>();
private string tagsScanId;
private DateTime readerStartedTime = DateTime.Now;
private volatile bool isRecvTags;//??????????
private volatile bool isStartCheckTags;//????????
private bool isCheckTags;//??????
private Thread checkTagsThread;
private string barcode = string.Empty;
private Stopwatch stopwatch;
private DateTime startDate;
bool hasBarcodeRead;
double weight;
SerialPort serialPort;
string portName;
double previousWeight;
string previousBarCode;

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
cmbPlcType.SelectedIndex = 0;

if (!Directory.Exists("log"))
Directory.CreateDirectory("log");

//??
Rovinj.Log.LogHelper.InitLogger(new Rovinj.Log.TextLog($"log\\
{DateTime.Now:yyyy-MM-dd}.log"));
hasBarcodeRead = false;
//Console.WriteLine("Program Starts");
//stopwatch = Stopwatch.StartNew();
////timer2.Start();
weight = 0;
portName = "COM3";
InitializeSerialPort(portName);
// Set the specific duration (e.g., 5 seconds)
//int specificDurationInSeconds = 5;

// Create a timer that checks the elapsed time every 100 milliseconds
//timer = new Timer(CheckElapsedTime, null, 0, 100);

//??
private void btn_Clear_Click(object sender, EventArgs e)
{
lblTagCount.Text = "0";
lblBoxCount.Text = "0";
listView1.Items.Clear();
epcList.Clear();
}

//??
private void button1_Click(object sender, EventArgs e)
{
try
{
if (btn_Connect.Text == "Connect")
{
double power = 30;
SilionReaderConfig readerConfig = new SilionReaderConfig()
{
Qvalue = 5,
Session = 1,
ReadTID = false,
Target = 0,
TagEncoding = 1,
IsFastRead = true,
QuickModeType = 3,
Antennas = new List<SilionAntennaConfig>(),
};

int antCount;
if (!int.TryParse(txtAntCount.Text, out antCount))//4??8???
antCount = 4;

for (int i = 0; i < antCount; i++)


{
readerConfig.Antennas.Add(new SilionAntennaConfig()
{
IsEnabled = true,
PortNumber = (ushort)(i + 1),
TxPowerInDbm = power
});
}
ConnectionConfig plcConnectionConfig = new ConnectionConfig();
if (radioButton1.Checked)
{
string[] address = txtPlcPort.Text.Split(':');
plcConnectionConfig.ConnectionMode = ConnectionMode.Serial;
plcConnectionConfig.SerialPortName = address[0];
plcConnectionConfig.BaudRate =
Convert.ToInt32(address[1]);//???9600
}
else
{
string[] address = txtPlcPort.Text.Split(':');
plcConnectionConfig.ConnectionMode =
ConnectionMode.Network;
plcConnectionConfig.NetworkAddress = address[0];
plcConnectionConfig.NetworkPort =
Convert.ToUInt16(address[1]);
}

ConnectionConfig readerConnectionConfig = new


ConnectionConfig();
readerConnectionConfig.Args = new object[]
{ antCount };//????,???4???,??1,2,4,8,16

if (radioButton4.Checked)
{
readerConnectionConfig.ConnectionMode =
ConnectionMode.Serial;
readerConnectionConfig.SerialPortName = txtReaderIp.Text;
}
else
{
readerConnectionConfig.ConnectionMode =
ConnectionMode.Network;
readerConnectionConfig.NetworkAddress = txtReaderIp.Text;
}

TunnelConfig tunnelConfig = new TunnelConfig()


{
PlcType = cmbPlcType.SelectedIndex == 0 ?
PlcType.Mitsubishi : PlcType.Siemens,
PlcConnectionConfig = plcConnectionConfig,
ReaderConnectionConfig = readerConnectionConfig,
ReaderConfig = readerConfig,
ReaderType = Rovinj.Tunnel.Reader.ReaderType.Silion
};

if (tunnelConfig.PlcType == PlcType.Siemens &&


tunnelConfig.PlcConnectionConfig.ConnectionMode == ConnectionMode.Serial)
{
MessageBox.Show("?????????!");
return;
}

tunnel = TunnelFactory.CreateTunnel(TunnelType.SC201,
tunnelConfig); // Here it is initializing the tunnel object
if (tunnel == null)
{
MessageBox.Show("Connect failed!");
return;
}

tunnel.TagsReported += Tunnel_TagsReported;
tunnel.ReaderStateChanged += Tunnel_ReaderStateChanged;
tunnel.PlcStateChanged += Tunnel_PlcStateChanged;
tunnel.ErrorReceived += Tunnel_ErrorReceived;
tunnel.SetM(3, true);

if (tunnel.Open())
{
//tunnel.SetM(3, true);
SoundPlayer player = new
SoundPlayer(Resources.InitSuccess);
player.Play();
MessageBox.Show("Connect Success!");
btn_Connect.Text = "Close";

IReader reader = tunnel.Devices["Reader"][0] as IReader;


ReaderCapability readerCapability = reader.GetCapability();
if (readerCapability != null)
{
cmbPower.Items.Clear();
//cmbModes.Items.Clear();

for (int i = 0; i < readerCapability.TxPowers.Count; i+


+)
{
cmbPower.Items.Add(readerCapability.TxPowers[i]);
}

//for (int i = 0; i <


readerCapability.ReaderModes.Count; i++)
//{
//
cmbModes.Items.Add(readerCapability.ReaderModes[i]);
//}

cmbPower.SelectedItem = Convert.ToDouble(30);
//cmbModes.SelectedItem = 0;
}
}
else
{
tunnel.Close();
MessageBox.Show("Connnect failed!");
}

//??
tunnel.Initialize();
}
else
{
CloseTunnel(null, null);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

private void btn_SetReader_Click(object sender, EventArgs e)


{
try
{
double power = Convert.ToDouble(cmbPower.SelectedItem);
SilionReaderConfig readerConfig = new SilionReaderConfig()
{
Qvalue = 5,
Session = 1,
ReadTID = chkReadTID.Checked,
Target = 0,
TagEncoding = 1,
IsFastRead = true,
QuickModeType = 3,
Antennas = new List<SilionAntennaConfig>(),
};

int antCount;
if (!int.TryParse(txtAntCount.Text, out antCount))//4??8???
antCount = 4;

for (int i = 0; i < antCount; i++)


{
readerConfig.Antennas.Add(new SilionAntennaConfig()
{
IsEnabled = true,
PortNumber = (ushort)(i + 1),
TxPowerInDbm = power
});
}

if (tunnel.SetReader(readerConfig))
{
if (chkReadTID.Checked)
tunnel.TunnelConfig.TagIdFieldName = "TID";
else
tunnel.TunnelConfig.TagIdFieldName = "EPC";

MessageBox.Show("?????????!");
}
else
{
MessageBox.Show("?????????!");
}
}
catch (Exception ex)
{
MessageBox.Show("?????????!" + ex.Message);
}
}

private void Tunnel_ReaderStateChanged(ITunnel tunnel,


TunnelReaderStateChangedEventArgs e)
{

if (e.RunningState == 0)
{
isStartCheckTags = false;
Invoke(new Action(() =>
{
lblReaderState.BackColor = Color.Red;
btn_StartReader.Text = "Start Read";
timer1.Enabled = false;
lblTimeCost.Text = (e.CreateTime -
readerStartedTime).ToString(@"mm\:ss\.fff");
//txtBarcode.Focus();
}));
}
else if (e.RunningState == 1)
{
tagsScanId = e.ScanId;
readerStartedTime = DateTime.Now;//???????
epcList.Clear();

if (isAutoMode)//?????
isStartCheckTags = true;

Invoke(new Action(() =>


{
lblReaderState.BackColor = Color.Green;
btn_StartReader.Text = "Stop Read";

//????
lblTagCount.Text = "0";
lblBoxCount.Text = "0";
listView1.Items.Clear();

//????
lblTimeCost.Text = "00:00.000";
timer1.Enabled = true;
//txtBarcode.Focus();
}));
}
else
{
Invoke(new Action(() => { lblReaderState.BackColor =
Color.DarkGray;
//txtBarcode.Focus();
}));
}

//if (txtBarcode.Text.Length > 0)


//{
// Invoke(new Action(() =>
// {
// txtBarcode.Clear();
// txtBarcode.Focus();
// }));

//}

private void Tunnel_PlcStateChanged(ITunnel tunnel,


TunnelPlcStateChangedEventArgs e) //also called when weight is placed
{

isAutoMode = e.PlcStatus.AutoMode;
Invoke(new Action(() =>
{
lblAutoMode.BackColor = e.PlcStatus.AutoMode ? Color.Green :
Color.Red;
lblShield.BackColor = e.PlcStatus.Shield ? Color.Green : Color.Red;
lblOpenState.BackColor = e.PlcStatus.OpenDoor ? Color.Green :
Color.Red;
lblG1.BackColor = e.PlcStatus.G1 ? Color.Green : Color.Red;
lblG2.BackColor = e.PlcStatus.G2 ? Color.Green : Color.Red;
lblG3.BackColor = e.PlcStatus.G3 ? Color.Green : Color.Red;
lblG4.BackColor = e.PlcStatus.G4 ? Color.Green : Color.Red;
lblG5.BackColor = e.PlcStatus.G5 ? Color.Green : Color.Red;
lblG6.BackColor = e.PlcStatus.G6 ? Color.Green : Color.Red;
lblG7.BackColor = e.PlcStatus.G7 ? Color.Green : Color.Red;
lblG8.BackColor = e.PlcStatus.G8 ? Color.Green : Color.Red;

// First step of curtains, means when weight is on weight machine


if (e.PlcStatus.FrontDoorUp && e.PlcStatus.RearDoorUp)
{
lblDoorOpen.BackColor = Color.Green;
//txtBarcode.Focus();
//GetWeight();
//hasBarcodeRead = true;
}
else
lblDoorOpen.BackColor = Color.Red;

// Second Step when weight is in the tunnel and curtains are closed
if (e.PlcStatus.FrontDoorDown && e.PlcStatus.RearDoorDown)
{
//txtBarcode.Clear();
//previousBarCode = barcode;
//previousWeight = weight;
lblDoorClose.BackColor = Color.Green;
//hasBarcodeRead = false;
weight = 0;
barcode = string.Empty;
}
else
lblDoorClose.BackColor = Color.Red;

// This is third step when box is scanned and curtains are open and
box is released
//if (!e.PlcStatus.FrontDoorUp && !e.PlcStatus.RearDoorUp
// && !e.PlcStatus.FrontDoorDown && !e.PlcStatus.RearDoorDown)
//{

//}

//// here we set focus of bar code field


//txtBarcode.Focus(); //only this will work
//txtBarcode.Enabled = true;
//txtBarcode.Clear();
//isBarcodeReading = false;
}));

//???????
private void Tunnel_ErrorReceived(ITunnel tunnel,
TunnelErrorReceivedEventArgs e)
{
Console.WriteLine($"????:{e.ErrorMessage},??:{e.Exception}");
}

//??????
private void Tunnel_TagsReported(ITunnel tunnel,
TunnelTagsReportedEventArgs e)
{
isRecvTags = true;
for (int i = 0; i < e.Tags.Count; i++)
{
Tag tag = e.Tags[i];
if (tag.ScanId != tagsScanId)
continue;

if (tunnel.TunnelConfig.TagIdFieldName == "TID" && !


string.IsNullOrEmpty(tag.TID))
{
if (epcList.Contains(tag.TID))
continue;

epcList.Add(tag.TID);
}
else
{
if (epcList.Contains(tag.EPC))
continue;

epcList.Add(tag.EPC);
}

BeginInvoke(new Action(() =>


{
//????
lblTagCount.Text = epcList.Count.ToString();

//??
if (int.TryParse(txtBoxTagCount.Text, out int boxTagCount) &&
boxTagCount > 0)
lblBoxCount.Text = Math.Ceiling((double)epcList.Count /
boxTagCount).ToString();

ListViewItem lv = new ListViewItem((listView1.Items.Count +


1).ToString());
lv.Tag = tag.EPC;
lv.SubItems.Add(tag.EPC);
lv.SubItems.Add(tag.TID);
lv.SubItems.Add(tag.Antenna.ToString());
lv.SubItems.Add(tag.RSSI.ToString());
lv.SubItems.Add(tag.ReadTime.ToString("yyyy-MM-dd HH:mm:ss"));
lv.SubItems.Add(tag.ScanId);
listView1.Items.Add(lv);
// txtBarcode.Focus();
}));
}
isRecvTags = false;
// here we set focus of bar code field
Invoke(new Action(() =>
{
txtBarcode.Focus(); //only this will work
txtBarcode.Enabled = true;
txtBarcode.Clear();
}));
}

//??????????????,???????????,?????????????????
private void CheckTagsThread()
{
while (isCheckTags)
{
if (!isStartCheckTags)
{
Thread.Sleep(10);
continue;
}

if (!int.TryParse(txtTotals.Text, out int total))


{
Thread.Sleep(10);
continue;
}

if (!int.TryParse(txtTimeout.Text, out int seconds))


{
Thread.Sleep(10);
continue;
}

if (isRecvTags)
{
Thread.Sleep(10);
continue;
}

if (readerStartedTime.AddSeconds(seconds) >= DateTime.Now)


{
if (epcList.Count == total)
{
isStartCheckTags = false;
SoundPlayer player = new
SoundPlayer(Resources.ReadTagsSuccess);
player.Play();
tunnel.ReadTagsSuccess();//????
}
else if (epcList.Count > total)
{
isStartCheckTags = false;
SoundPlayer player = new
SoundPlayer(Resources.ReadTagsFailed);
player.Play();
tunnel.ReadTagsFailed();//????,????
}
}
else//????
{
isStartCheckTags = false;
SoundPlayer player = new SoundPlayer(Resources.ReadTagsFailed);
player.Play();
tunnel.ReadTagsFailed();//????
}

Thread.Sleep(10);
}
}

private void CloseTunnel(object sender, EventArgs e)


{
if (tunnel == null)
return;

if (btn_StartReader.Text == "Stop Read")


{
tunnel.StopReader();
btn_StartReader.Text = "Start Read";
}

if (btn_Start.Text == "Stop")
{
tunnel.Stop();
btn_Start.Text = "Run";

isCheckTags = false;
if (checkTagsThread != null)
checkTagsThread.Join();
}

//??????
checkBox2.Checked = false;

tunnel.Close();
tunnel = null;
btn_Connect.Text = "Connect";
}

/// <summary>
/// ??
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_Start_Click(object sender, EventArgs e)
{
// focus of barcode
//txtBarcode.Focus();

if (tunnel == null)
return;

if (btn_Start.Text == "Run")
{
if (tunnel.Start())
{
btn_Start.Text = "Stop";
lblAutoMode.BackColor = Color.Red;
lblShield.BackColor = Color.Red;
lblOpenState.BackColor = Color.Red;
lblG1.BackColor = Color.Red;
lblG2.BackColor = Color.Red;
lblG3.BackColor = Color.Red;
lblG4.BackColor = Color.Red;
lblG5.BackColor = Color.Red;
lblG6.BackColor = Color.Red;
lblG7.BackColor = Color.Red;
lblG8.BackColor = Color.Red;
lblDoorOpen.BackColor = Color.Red;
lblDoorClose.BackColor = Color.Red;

isCheckTags = true;
checkTagsThread = new Thread(CheckTagsThread);
checkTagsThread.IsBackground = true;
checkTagsThread.Start();
}
}
else
{
tunnel.Stop();
btn_Start.Text = "Run";

isCheckTags = false;
if (checkTagsThread != null)
checkTagsThread.Join();
}
}

private void btn_StartReader_Click(object sender, EventArgs e)


{
if (tunnel == null)
return;

if (btn_StartReader.Text == "Start Read")


{
btn_Clear_Click(null, null);
tunnel.StartReader();
btn_StartReader.Text = "Stop Read";
}
else
{
tunnel.StopReader();
btn_StartReader.Text = "Start Read";
}
}

/// <summary>
/// ????
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_ReadTagSuccess_Click(object sender, EventArgs e)
{
if (tunnel == null)
return;

isStartCheckTags = false;
if (!tunnel.ReadTagsSuccess())
MessageBox.Show($"?{btn_ReadTagSuccess.Text}???????!");
}

/// <summary>
/// ????
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_ReadTagFailed_Click(object sender, EventArgs e)
{
if (tunnel == null)
return;

isStartCheckTags = false;
if (!tunnel.ReadTagsFailed())
MessageBox.Show($"?{btn_ReadTagFailed.Text}???????!");
}

private void btn_OpenDoor_Click(object sender, EventArgs e)


{
if (tunnel == null)
return;

if (!tunnel.OpenDoor())
MessageBox.Show($"?{btn_OpenDoor.Text}???????!");
}

private void btn_CloseDoor_Click(object sender, EventArgs e)


{
if (tunnel == null)
return;

if (!tunnel.CloseDoor())
MessageBox.Show($"?{btn_CloseDoor.Text}???????!");
}

private void btn_ScanSuccess_Click(object sender, EventArgs e)


{
// <Here add the barcode login>

//listView1.Clear();
//txtBarcode.Focus();
//string val = txtBarcode.Text;

// </Here add the barcode login>


if (tunnel == null)
return;

if (!tunnel.ScanBarcodeSuccess())
MessageBox.Show($"?{btn_ScanSuccess.Text}???????!");
}

private void btn_ScanFailed_Click(object sender, EventArgs e)


{
if (tunnel == null)
return;

if (!tunnel.ScanBarcodeFailed())
MessageBox.Show($"?{btn_ScanFailed.Text}???????!");
}

private void btn_Weighed_Click(object sender, EventArgs e)


{
if (tunnel == null)
return;

if (!tunnel.WeighingCompleted())
MessageBox.Show($"?{btn_Weighed.Text}???????!");
}

private void radioButton2_CheckedChanged(object sender, EventArgs e)


{
if (radioButton2.Checked)
{
txtPlcPort.Text = "192.168.1.250:5556";
}
}

private void radioButton1_CheckedChanged(object sender, EventArgs e)


{
if (radioButton1.Checked)
{
txtPlcPort.Text = "COM3:9600";
}
}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)


{
CloseTunnel(null, null);
}

/// <summary>
/// ?????????,????????????,????
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
tunnel.DemonstrationMode(checkBox2.Checked);
}

private void timer1_Tick(object sender, EventArgs e)


{
lblTimeCost.Text = (DateTime.Now -
readerStartedTime).ToString(@"mm\:ss\.fff");
}

private void listView1_MouseDown(object sender, MouseEventArgs e)


{
if (e.Button == MouseButtons.Right)
contextMenuStrip1.Show(listView1, e.Location);
}

private void btnExport_Click(object sender, EventArgs e)


{
if (listView1.Items.Count == 0)
return;

try
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = DateTime.Now.ToString("yyyyMMHHddmmss") +
".csv";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
FileStream fs = new FileStream(saveFileDialog.FileName,
FileMode.Create, FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(fs);

string header = "EPC,TID,Antenna,RSSI,ReadTime,ScanId";


sw.WriteLine(header);

for (int i = 0; i < listView1.Items.Count; i++)


{
ListViewItem lv = listView1.Items[i];
string item = $"{lv.SubItems[1].Text},
{lv.SubItems[2].Text},{lv.SubItems[3].Text},{lv.SubItems[4].Text},
{lv.SubItems[5].Text},{lv.SubItems[6].Text}";
sw.WriteLine(item);
}

sw.Close();
fs.Close();
MessageBox.Show("????!");
}
}
catch (Exception ex)
{
MessageBox.Show("????!" + ex.Message);
}
}

//private void txtBarcode_KeyDown(object sender, KeyEventArgs e)


//{
// if (!stopwatch.IsRunning)
// {
// startDate = DateTime.Now;
// stopwatch.Start();
// await WaitAndStop();
// }
// if (DateTime.Now >= startDate.AddSeconds(1))
// {
// txtBarcode.Enabled = false;
// stopwatch.Stop();
// }
//}

//private async Task WaitAndStop()


//{
// await Task.Delay(5);
// stopwatch.Stop();
// txtBarcode.Enabled = false;
//}
//private void CheckElapsedTime(object state)
//{
// // Check if the elapsed time has reached the specific duration
// if (stopwatch.Elapsed.TotalSeconds >= 3)
// {
// // Invoke your function or event here
// YourFunction();

// // Optionally reset the stopwatch for the next interval


// stopwatch.Restart();
// }
//}

private void timer2_Tick(object sender, EventArgs e)


{
//MessageBox.Show("Timer 2 clicked");
barcode = txtBarcode.Text;
if (!string.IsNullOrWhiteSpace(barcode) && weight > 0.3 &&
hasBarcodeRead)
{
btn_ScanSuccess.PerformClick();
weight = 0;
hasBarcodeRead = false;
}
}

private void GetWeight()


{
//serialPort.Open();//;string Text = serialPort.ReadLine().ToString();
if (!serialPort.IsOpen)
{
serialPort.Open();//;string Text =
serialPort.ReadLine().ToString();

weight = 0;
for (int i = 0; i < 6; i++)
{
int data = serialPort.BytesToRead;
byte[] buf = new byte[8];
int nread = serialPort.Read(buf, 0, 8);
string strRecv = Encoding.ASCII.GetString(buf);
string strWeight = new string(strRecv.Substring(1,
strRecv.Length - 1).Reverse().ToArray());
weight += Convert.ToDouble(strWeight);
}
weight = Math.Round((double)weight / 6, 2);
lblWeight.Text = weight.ToString();
}
}

void InitializeSerialPort(string portName)


{
serialPort = new SerialPort(portName, 9600, Parity.None, 8,
StopBits.One);

// You may need to adjust the serial port settings based on your weight
machine specifications
// Other serial port settings (if needed)
serialPort.Handshake = Handshake.None;
serialPort.RtsEnable = true;
serialPort.DtrEnable = true;
//serialPort.ReadTimeout = 500; // Set an appropriate read timeout
//serialPort.WriteTimeout = 500; // Set an appropriate write timeout
}

//private async void txtBarcode_KeyDown(object sender, KeyEventArgs e)


//{

//}

private async Task CalculateIntervals()


{
await Task.Delay(500);
txtBarcode.Enabled = false;
btn_ScanSuccess.PerformClick();
GetWeight();
}
}
}

You might also like